我正在使用XMLHttpRequest
将文件上传到Node.JS服务器。我需要监控进度,但是在触发上传后几乎可以立即收到100%的收益!但是我在Google Chrome浏览器的“网络”标签中看到上传正在进行中。我认为问题出在CORS。是否有人有解决此问题的想法?
在Stack Overflow上有几个这样的问题,但是针对它们的答案根本不能解决我的问题。 This question也不能解决我的问题。
我的代码的简化版本:
function uploadFile(file, headers, endpoint) {
const xhr = new XMLHttpRequest();
const formData = new FormData();
formData.append('file', file.slice(), file.name);
xhr.open('POST', endpoint, true);
Object.entries(headers).forEach(([header, value]) => {
xhr.setRequestHeader(header, value);
});
xhr.upload.addEventListener('progress', ({ loaded, total, lengthComputable }) => {
if (lengthComputable) {
console.log(loaded / total * 100);
}
});
xhr.send(formData);
}
我从服务器(JSON)收到这样的响应:
{
"indent_size": "4",
"indent_char": " ",
"max_preserve_newlines": "5",
"preserve_newlines": true,
"brace_style": "collapse",
"space_before_conditional": true,
"unescape_strings": false,
"jslint_happy": false,
"end_with_newline": false,
"wrap_line_length": "0"
}