Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 424
Mattias Petter Johansson Avatar asked Apr 13 '16 16:04

Mattias Petter Johansson


People also ask

What is XMLHttpRequest fetch API?

May 17, 2021 3 min read API. The Fetch API allows you to make network requests similar to XMLHttpRequest (XHR). The main difference is that the Fetch API uses Promises, which enables a simpler and cleaner API, avoiding callback hell and having to remember the complex API of XMLHttpRequest.

Is fetch the same as XMLHttpRequest?

It is an improvement over the XMLHttpRequest API. The main difference between Fetch and XMLHttpRequest is that the Fetch API uses Promises, hence avoiding callback hell . If you are new to promises then check out JavaScript Promises: an Introduction .

What can be used instead of XMLHttpRequest?

The Fetch API is a modern alternative to XMLHttpRequest . The generic Headers, Request, and Response interfaces provide consistency while Promises permit easier chaining and async/await without callbacks.

Does fetch use XMLHttpRequest?

Fortunately, the response object that fetch() returns includes an ok property that we can use to determine whether the API call was successful or not. While the Fetch API uses an XMLHttpRequest object under the hood, they don't contain all of the same properties.


1 Answers

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.

like image 178
Staś Małolepszy Avatar answered Nov 15 '22 13:11

Staś Małolepszy