简体   繁体   English

什么是XMLHttpRequest.send(文件)的Fetch API等价物?

[英]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. 我正在尝试将客户端重构为XMLHttpRequest的旧后端,而不是使用Fetch API,我很难弄清楚下面代码中xhr.send(文件)的Fetch API等价物。

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. fetch可以使用第二个参数 init ,它指定请求的高级选项。 In particular, you can specify the method and the body options: 特别是,您可以指定methodbody选项:

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

You can also pass the same options to the Request constructor . 您还可以将相同的选项传递给Request 构造函数

body must a Blob, BufferSource, FormData, URLSearchParams, or USVString object. body必须是Blob,BufferSource,FormData,URLSearchParams或USVString对象。 Fortunately, File objects are just a special kind of Blobs, and can be used everywhere where Blobs are accepted . 幸运的是,File对象只是一种特殊的Blob,可以在任何接受Blob的地方使用。

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://github.com/github/fetch

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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