新聞中心
如何在Node.js中獲取文件上傳進度?針對這個問題,這篇文章詳細介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
利用progress-stream獲取文件上傳進度
如果只是想在服務(wù)端獲取上傳進度,可以試下如下代碼。注意,這個模塊跟Express、multer并不是強綁定關(guān)系,可以獨立使用。
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) { // 創(chuàng)建progress stream的實例 var progress = progressStream({length: '0'}); // 注意這里 length 設(shè)置為 '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類型,需要監(jiān)聽length來獲取文件真實大小。(官方文檔里是通過conviction事件,其實是有問題的)
// 獲取上傳文件的真實長度(針對 multipart) progress.on('length', function nowIKnowMyLength (actualLength) { console.log('actualLength: %s', actualLength); progress.setLength(actualLength); });
3、關(guān)于progress-stream獲取真實文件大小的bug?
針對multipart文件上傳,progress-stream 實例子初始化時,參數(shù)length需要傳遞非數(shù)值類型,不然你獲取到的進度要一直是0,最后就直接跳到100。
至于為什么會這樣,應(yīng)該是 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'])); } }); });
關(guān)于如何在Node.js中獲取文件上傳進度問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注創(chuàng)新互聯(lián)成都網(wǎng)站設(shè)計公司行業(yè)資訊頻道了解更多相關(guān)知識。
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機、免備案服務(wù)器”等云主機租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場景需求。
網(wǎng)頁題目:如何在Node.js中獲取文件上傳進度-創(chuàng)新互聯(lián)
文章轉(zhuǎn)載:http://www.dlmjj.cn/article/cohhgg.html