在同一个HTTP请求中发送多个块



在浏览器JavaScript中,是否有一种方法可以"打开HTTP请求";和写/发送数据到它像一个文件句柄,并有API读取这个作为一个HTTP请求?还是对多个HTTP请求进行分块处理是唯一的方法?(我认为是这样,因为分块是一种流行的方法)

const req = new HTTPConnection("PUT", url);
async for (const chunk of asyncDataSource) {
req.write(chunk);
}
req.close();

您可以使用Fetch API或老式的XmlHttpRequest

来实现这一点我猜你想上传一些文件或图像/视频?

可以这样写XmlHttpRequest:

const fileInput = document.querySelector("input[type=file]");
const file = fileInput.files[0];
const req = new XMLHttpRequest();
req.open("PUT", url);
req.setRequestHeader("Content-Type", file.type);
req.onreadystatechange = function() {
if (req.readyState === 4 && req.status === 200) {
console.log(req.responseText);
}
};
req.send(file);

或者更现代的Fetch API:

const fileInput = document.querySelector("input[type=file]");
const file = fileInput.files[0];
const body = new FormData();
body.append("file", file);
fetch(url, {
method: "PUT",
body: body,
headers: {
"Content-Type": file.type,
},
})
.then((res) => res.json())
.then((json) => console.log(json));

最新更新