Mattias Petter Johansson Mattias Petter Johansson - 6 months ago 29
Javascript Question

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);
}

Answer

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.