完成百分比的流

时间:2013-07-22 21:48:43

标签: node.js

我需要使用requestsuperagent等内容将base64中的文件流式传输到http端点。找出文件上传百分比的最佳方法是什么?

我假设我可以使用以下内容创建读取流:

fs.createReadStream('/tmp/cats.jpg', {encoding: 'base64'})

使用上述库中的一个的任何示例都将非常感激。

3 个答案:

答案 0 :(得分:3)

我一直在寻找类似问题的答案,多亏了Alberto Zaccagni的回答,我得到了一些代码。

因此,对于那些不想自己拼图的人来说,这里是代码(为Stackoverflow编辑):

var zipfile = "my_large_archive.zip";

// Get the size of the file
fs.stat(zipfile, function (err, stats) {
    var zipSize         = stats.size;
    var uploadedSize    = 0; // Incremented by on('data') to keep track of the amount of data we've uploaded

    // Create a new read stream so we can plug events on it, and get the upload progress
    var zipReadStream   = fs.createReadStream(zipfile);

    zipReadStream.on('data', function(buffer) {
        var segmentLength   = buffer.length;

        // Increment the uploaded data counter
        uploadedSize        += segmentLength;

        // Display the upload percentage
        console.log("Progress:\t",((uploadedSize/zipSize*100).toFixed(2)+"%"));
    });

    // Some other events you might want for your code
    zipReadStream.on('end', function() {
        console.log("Event: end");
    });
    zipReadStream.on('close', function() {
        console.log("Event: close");
    });


    var formData    = require('form-data');
    var form        = new formData();

    form.append('apikey', 'f4sd5f4sdf6ds456');  // Just some post parameters I need to send to the upload endpoint
    form.append('file', zipReadStream);         // The zip file, passed as a fs.createReadStream instance

    // Submit the form and the file
    form.submit('http://www.someserver.com/upload', function(err, res) {
        if (err) {
            console.log("Oups! We encountered an error :(\n\n", err);
            return false;
        }
        console.log("Your file has been uploaded.");
        res.resume();   // Fix is you use that code for a CLI, so that the execution will stop and let users enter new commands
    });
});

答案 1 :(得分:1)

我认为你可以使用progress-stream

答案 2 :(得分:0)

在nodejs中,我们有Readable stream,它在收到大量数据时会发出data事件,通过知道文件大小,您可以轻松跟踪通过{{{ 1}}事件接收器,然后更新百分比。

使用

获取文件维度
data