How do I upload a file with the JS fetch API?

deitch picture deitch · Mar 17, 2016 · Viewed 168.8k times · Source

I am still trying to wrap my head around it.

I can have the user select the file (or even multiple) with the file input:

<form>
  <div>
    <label>Select file to upload</label>
    <input type="file">
  </div>
  <button type="submit">Convert</button>
</form>

And I can catch the submit event using <fill in your event handler here>. But once I do, how do I send the file using fetch?

fetch('/files', {
  method: 'post',
  // what goes here? What is the "body" for this? content-type header?
}).then(/* whatever */);

Answer

Integ picture Integ · Nov 27, 2016

I've done it like this:

var input = document.querySelector('input[type="file"]')

var data = new FormData()
data.append('file', input.files[0])
data.append('user', 'hubot')

fetch('/avatars', {
  method: 'POST',
  body: data
})