我正在尝试将客户端从 XMLHttpRequest 重构为旧后端以改用 Fetch API,但我很难弄清楚下面代码中与 xhr.send(file) 等效的 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
可以获取 second argument , init
, 指定请求的高级选项。特别是,您可以指定 method
和 body
选项:
fetch(url, {
method: 'POST',
headers: new Headers({
"Content-Type": "image/jpeg",
}),
body: file,
})
您还可以将相同的选项传递给Request
constructor .
body
必须是 Blob、BufferSource、FormData、URLSearchParams 或 USVString 对象。幸运的是,File 对象只是一种特殊的 Blob,可以使用 everywhere where Blobs are accepted .
关于javascript - XMLHttpRequest.send(file) 的 Fetch API 等价物是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36604865/