The FormData Object and XMLHttpRequest by Flavio Copes

Description

The FormData object is part of the XMLHttpRequest 2 spec .

It’s available in all the modern browsers but keep in mind that IE versions prior to 10 do not support it.

Here is one example of using FormData to send the content of a file using an XHR connection:

<input type="file" id="fileUpload" />
const sendFile = file => {
  const uri = '/saveImage'
  const xhr = new XMLHttpRequest()
  const fd = new FormData()

  xhr.open('POST', uri, true)
  xhr.onreadystatechange = () => {
    if (xhr.readyState == 4 && xhr.status == 200) {
      const imageName = xhr.responseText
      //do what you want with the image name returned
      //e.g update the interface
    }
  }
  fd.append('myFile', file)
  xhr.send(fd)
}

const handleImageUpload = event => {
  const files = event.target.files
  sendFile(files[0])
}

document.querySelector('#fileUpload').addEventListener('change', event => {
  handleImageUpload(event)
})

This snippet instead can be used to send multiple files:

<input type="file" id="fileUpload" multiple />
const sendFiles = files => {
  const uri = '/saveImage'
  const xhr = new XMLHttpRequest()
  const fd = new FormData()

  xhr.open('POST', uri, true)
  xhr.onreadystatechange = () => {
    if (xhr.readyState == 4 && xhr.status == 200) {
      const imageName = xhr.responseText
      //do what you want with the image name returned
      //e.g update the interface
    }
  }

  for (let i = 0; i < files.length; i++) {
    fd.append(files[i].name, files[i])
  }

  xhr.send(fd)
}

const handleImageUpload = event => {
  sendFiles(event.target.files)
}

document.querySelector('#fileUpload').addEventListener('change', event => {
  handleImageUpload(event)
})