如果只是想在服务端获取上传进度,可以试下如下代码。注意,这个模块跟Express、multer并不是强绑定关系,可以独立使用。 var fs = require('fs'); var express = require('express'); var multer = require('multer'); var progressStream = require('progress-stream');
var app = express(); var upload = multer({ dest: 'upload/' });
app.post('/upload', function (req, res, next) { // 创建progress stream的实例 var progress = progressStream({length: '0'}); // 注意这里 length 设置为 '0' req.pipe(progress); progress.headers = req.headers;
// 获取上传文件的真实长度(针对 multipart)
progress.on('length', function nowIKnowMyLength (actualLength) {
console.log('actualLength: %s', actualLength);
progress.setLength(actualLength);
});
// 获取上传进度
progress.on('progress', function (obj) {
console.log('progress: %s', obj.percentage);
});
// 实际上传文件
upload.single('logo')(progress, res, next);
});
app.post('/upload', function (req, res, next) { res.send({ret_code: '0'}); });
app.get('/form', function(req, res, next){ var form = fs.readFileSync('./form.html', {encoding: 'utf8'}); res.send(form); });
app.listen(3000);
获取上传文件的真实大小: multipart类型,需要监听length来获取文件真实大小。(官方文档里是通过conviction事件,其实是有问题的) // 获取上传文件的真实长度(针对 multipart) progress.on('length', function nowIKnowMyLength (actualLength) { console.log('actualLength: %s', actualLength); progress.setLength(actualLength); });
关于progress-stream获取真实文件大小的bug? 针对multipart文件上传,progress-stream 实例子初始化时,参数length需要传递非数值类型,不然你获取到的进度要一直是0,最后就直接跳到100。 至于为什么会这样,应该是 progress-steram 模块的bug,看下模块的源码。当length是number类型时,代码直接跳过,因此你length一直被认为是0。
tr.on('pipe', function(stream) { if (typeof length === 'number') return; // Support http module if (stream.readable && !stream.writable && stream.headers) { return onlength(parseInt(stream.headers['content-length'] || 0)); }
// Support streams with a length property
if (typeof stream.length === 'number') {
return onlength(stream.length);
}
// Support request module
stream.on('response', function(res) {
if (!res || !res.headers) return;
if (res.headers['content-encoding'] === 'gzip') return;
if (res.headers['content-length']) {
return onlength(parseInt(res.headers['content-length']));
}
});
});