简体   繁体   中英

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

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM