use*_*315 4 upload xmlhttprequest node.js express multer
我正在尝试使用XHR来跟踪上传进度,但是在event.total上我的onprogress回调我只从响应头获取Content-Length而不是上传文件大小:
xhr.onprogress = (event) => {
console.log('Progress ' + event.loaded + '/' + event.total);
}
Run Code Online (Sandbox Code Playgroud)
我使用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...');
});
Run Code Online (Sandbox Code Playgroud)
但是它的工作方式相同,我只在日志和XHR onprogress事件中获得"Progress ...".我只有Content-Length值而不是文件大小值.请帮助,我不知道如何解决它!
dan*_*per 17
如果要显示进度,则无需在后端获取进度,只需要知道从前端发送到后端的内容,以便计算上载进度.
在你的前端.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);
Run Code Online (Sandbox Code Playgroud)
在后端,您只需要一个这样的简单端点:
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();
});
Run Code Online (Sandbox Code Playgroud)
Multer也是必要的,记住,xhr只适用于现代浏览器.
| 归档时间: |
|
| 查看次数: |
6390 次 |
| 最近记录: |