Pure JavaScript File Upload Example |Video upload date:  · Duration: PT8M21S  · Language: EN

Learn a compact pure JavaScript file upload example with drag and drop progress and server POST using FormData and XMLHttpRequest

Why this guide exists

If you are building a frontend that accepts files and you want it to feel less like a 1999 FTP client this upload tutorial is for you. We will show a JavaScript file upload flow that supports drag and drop and a progress bar while keeping the code tiny and understandable. This is practical web development not a magic trick.

What you will get

  • Simple HTML with a file input and a drop zone
  • A FormData based upload using XMLHttpRequest for real time progress
  • A friendly progress bar and basic server response handling

Minimal HTML to start

Keep the markup tiny so you can paste it into a sandbox and stop blaming the browser.

<input id='fileInput' type='file' multiple>
<div id='dropZone' style='padding:20px;border:2px dashed #ccc;margin-top:10px'>Drop files here</div>
<div id='progressBar' style='width:100%;background:#eee;margin-top:10px'>
  <div id='progressFill' style='width:0%;background:#4caf50;text-align:center;color:#fff'></div>
</div>

Hook up drag and drop and file selection

Both file input and drag and drop are supported so users can choose their level of dramatic flair.

const fileInput = document.getElementById('fileInput')
fileInput.addEventListener('change', e => handleFiles(e.target.files))

const dropZone = document.getElementById('dropZone')
dropZone.addEventListener('dragover', e => e.preventDefault())
dropZone.addEventListener('drop', e => {
  e.preventDefault()
  handleFiles(e.dataTransfer.files)
})

function handleFiles(files) {
  Array.from(files).forEach(file => uploadFile(file))
}

Upload with FormData and XMLHttpRequest

We use FormData and XMLHttpRequest so the browser handles multipart boundaries and you get upload progress events without dark rituals.

function uploadFile(file) {
  const fd = new FormData()
  fd.append('file', file)

  const xhr = new XMLHttpRequest()
  xhr.open('POST', '/upload')

  xhr.upload.addEventListener('progress', e => {
    if (e.lengthComputable) {
      const percent = Math.round(e.loaded / e.total * 100)
      updateProgress(percent)
    }
  })

  xhr.addEventListener('load', () => {
    handleResponse(xhr.responseText)
  })

  xhr.addEventListener('error', () => {
    showMessage('Upload failed, try again')
  })

  xhr.send(fd)
}

Important note about headers

Do not manually set the content type for multipart form uploads. Let the browser set the boundary. If you try to be clever and set headers yourself the server will hate you.

Progress UI and response handling

A tiny progress bar keeps users from assuming the file was sent to a black hole. Update the fill width and show a percent number.

function updateProgress(percent) {
  const fill = document.getElementById('progressFill')
  fill.style.width = percent + '%'
  fill.textContent = percent + '%'
}

function handleResponse(text) {
  try {
    const json = JSON.parse(text)
    showMessage(json.message || 'Upload complete')
  } catch (err) {
    showMessage('Upload complete')
  }
}

function showMessage(msg) {
  console.log(msg)
  // Replace with UI code to show messages to the user
}

Tips from someone who has broken uploads many times

  • Test large files and check server timeouts
  • Use xhr.upload progress for frontend progress not server side events
  • Keep the server response JSON friendly so handleResponse does not cry

Wrap up

This AJAX file upload pattern using JavaScript FormData and XMLHttpRequest is reliable and easy to integrate into typical web development stacks. Add validation and nice error handling and your users will upload files without staging a revolt.

I know how you can get Azure Certified, Google Cloud Certified and AWS Certified. It's a cool certification exam simulator site called certificationexams.pro. Check it out, and tell them Cameron sent ya!

This is a dedicated watch page for a single video.