Mattias Petter Johansson
Mattias Petter Johansson

Reputation: 1074

What is the Fetch API equivalent of XMLHttpRequest.send(file)?

I am trying to refactor a client to an old backend from XMLHttpRequest to use the Fetch API instead, and I am having a hard time figuring out what the Fetch API equivalent of xhr.send(file) is in the code below.

input.addEventListener('change', function(event) {
  var file = event.target.files[0];
  var url = 'https://somedomain.com/someendpoint';
  var xhr = new XMLHttpRequest();
  xhr.open('POST', url, true);
  xhr.setRequestHeader('Content-Type', 'image/jpeg');
  xhr.send(file);
}

Upvotes: 12

Views: 2430

Answers (2)

Gilles Castel
Gilles Castel

Reputation: 1184

This can be done like this:

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

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

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

https://github.com/github/fetch

https://developer.mozilla.org/en-US/docs/Web/API/FormData

Upvotes: 4

Stanisław Małolepszy
Stanisław Małolepszy

Reputation: 766

fetch can take a second argument, init, which specifies advanced options of the request. In particular, you can specify the method and the body options:

fetch(url, {
  method: 'POST',
  headers: new Headers({
    "Content-Type": "image/jpeg",
  }),
  body: file,
})

You can also pass the same options to the Request constructor.

body must a Blob, BufferSource, FormData, URLSearchParams, or USVString object. Fortunately, File objects are just a special kind of Blobs, and can be used everywhere where Blobs are accepted.

Upvotes: 15

Related Questions