问题描述
我正在尝试使用XHR来跟踪上传进度,但是在event.total的onprogress回调中,我仅从响应标头获取Content-Length而不是上传文件大小:
I am trying to use XHR to track uploading progress, but at my onprogress callback at event.total I only getting Content-Length from response header instead of uploading file size:
xhr.onprogress = (event) => {
console.log('Progress ' + event.loaded + '/' + event.total);
}
我使用Multer处理文件上传,默认情况下似乎无法处理文件上传: https://github.com/expressjs/multer/issues/243
I use Multer to handle file uploading and seems it is not avaible to handle file uploading by default:https://github.com/expressjs/multer/issues/243
所以我试图通过进度流来处理上传:
So I tried to handle uploading with progress-stream:
var p = progress({ time: 1 });
request.pipe(p);
p.on('progress', function() {
console.log('Progress...');
});
但是它以相同的方式工作,我只在日志和XHR onprogress event上得到"Progress ...".总的来说,我只有Content-Length值,而不是文件大小值.请帮忙,我不知道如何解决!
But it works same way, I only get onle "Progress..." at log and at XHR onprogress event.total I have only Content-Length value instead of file size value. Help please, I have no idea how to fix it!
推荐答案
如果要显示进度,则不需要在后端获取进度,只需要知道从前端发送到的内容即可后端,以便您可以计算上传进度.
You don't need get the progress in the backend if you want to show the progress, you only need to know what you've sent from your frontend to backend so you can calculate the upload progress.
在前端.js或.html中,尝试执行以下操作:
In your frontend .js or .html, try something like this:
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);
在后端,您只需要一个简单的端点,像这样:
In the backend you only need a simple endpoint like this:
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仅在现代浏览器中有效.
Multer is also necessary and remember, xhr only works in modern browsers.
这篇关于使用ExpressJS Multer时XHR上传进度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!