我正在尝试使用XHR来跟踪上传进度,但是在event.total上我的onprogress回调我只从响应头获取Content-Length而不是上传文件大小:
xhr.onprogress = (event) => {
console.log('Progress ' + event.loaded + '/' + event.total);
}
我使用Multer处理文件上传,默认情况下无法处理文件上传: https://github.com/expressjs/multer/issues/243
所以我尝试使用progress-stream处理上传:
var p = progress({ time: 1 });
request.pipe(p);
p.on('progress', function() {
console.log('Progress...');
});
但是它的工作方式相同,我只是进步了#34;进步......"在log和XHR onprogress event.total我只有Content-Length值而不是文件大小值。求助,我不知道如何解决它!
答案 0 :(得分:17)
如果您想要显示进度,您不需要在后端获得进度,您只需要知道从前端发送到后端的内容,这样您就可以计算上传进度。< / p>
在您的前端.js或.html中,尝试以下内容:
var formData = new FormData();
var file = document.getElementById('myFile').files[0];
formData.append('myFile', file);
var xhr = new XMLHttpRequest();
// your url upload
xhr.open('post', '/urluploadhere', true);
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var percentage = (e.loaded / e.total) * 100;
console.log(percentage + "%");
}
};
xhr.onerror = function(e) {
console.log('Error');
console.log(e);
};
xhr.onload = function() {
console.log(this.statusText);
};
xhr.send(formData);
在后端你只需要一个这样的简单终点:
app.post('/urluploadhere', function(req, res) {
if(req.files.myFile) {
console.log('hey, Im a file and Im here!!');
} else {
console.log('ooppss, may be you are running the IE 6 :(');
}
res.end();
});
Multer也是必要的,请记住,xhr只适用于现代浏览器。