使用expressjs multer时xhr上传进度
xhr uploading progress while using expressjs multer
我正在尝试使用 XHR 来跟踪上传进度,但在 event.total 的 onprogress 回调中,我仅从响应 header 中获得 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...');
});
但它的工作方式相同,我在日志和 XHR onprogress event.total 中只得到 "Progress..." 我只有 Content-Length 值而不是文件大小值。请帮忙,我不知道如何解决它!
如果你想显示进度,你不需要在后端获取进度,你只需要知道你从前端发送到后端,就可以计算上传进度。
在您的前端 .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 仅适用于现代浏览器。
我正在尝试使用 XHR 来跟踪上传进度,但在 event.total 的 onprogress 回调中,我仅从响应 header 中获得 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...');
});
但它的工作方式相同,我在日志和 XHR onprogress event.total 中只得到 "Progress..." 我只有 Content-Length 值而不是文件大小值。请帮忙,我不知道如何解决它!
如果你想显示进度,你不需要在后端获取进度,你只需要知道你从前端发送到后端,就可以计算上传进度。
在您的前端 .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 仅适用于现代浏览器。