上传进度 - 请求

时间:2012-08-23 19:29:06

标签: node.js coffeescript

我使用Request上传文件。

req = request.post url: "http://foo.com", body: fileAsBuffer, (err, res, body) ->
    console.log "Uploaded!"

我如何知道实际上传了多少数据?是否有一些我可以订阅的事件,或者我可以查询request的属性?

如果没有,那么上传数据并知道上传了多少内容的最佳方法是什么?

5 个答案:

答案 0 :(得分:8)

我需要处理我的另一个项目的上传进度。

我发现您可以轮询request的{​​{1}}财产。

例如:

connection._bytesDispatched

注意:如果您要转到r = request.post url: "http://foo.com", body: fileAsBuffer setInterval (-> console.log "Uploaded: #{r.req.connection._bytesDispatched}"), 250 ,请改为投票r

答案 1 :(得分:6)

我花了几个小时在request<?php $text = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option. Mirum est notare quam littera gothica quam nunc putamus parum claram anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima."; $charnum="300"; $number=strlen($text); $repeat=$number/$charnum; $newtext= str_replace("\n", "", $text); $newtext = wordwrap($newtext, $charnum, "\n"); $newtext = explode("\n", $newtext); $keywords = explode("\n", file_get_contents('keywords.txt')); $title = $keywords[ array_rand($keywords) ]; $cat = explode("\n", file_get_contents('cat.txt')); $cat = $keywords[ array_rand($keywords) ]; $tag = explode("\n", file_get_contents('tag.txt')); $tag = $keywords[ array_rand($keywords) ]; $newtext=substr_replace($newtext, '"csv_post_title"/"csv_post_type"/"csv_post_categories"/"csv_post_tags"/"csv_post_post"/"csv_post_date"/"csv_post_excerpt"',0,0); $newtext=substr_replace($newtext, "\n",121,0); $newtext=substr_replace($newtext, '"'.$title.'"/""/"'.$cat.'"/"'.$tag.'"/',0,0); for ( $count=1 ; $count < $repeat ; $count++ ) { $file = "$count.txt"; file_put_contents($file,$newtext[$count]); } ?> 来源找到任何有效的内容,最后找到了一种不同的方法,这对我来说更合适。

我们可以依赖drain事件和bytesWritten属性:

node

或者,如果您需要处理文件字节的进度,则更容易使用流data事件:

request.put({
  url: 'https://example.org/api/upload',
  body: fs.createReadStream(path)
}).on('drain', () => {
  console.log(req.req.connection.bytesWritten);
});

流缓冲区大小为let size = fs.lstatSync(path).size; let bytes = 0; request.put({ url: 'https://example.org/api/upload', body: fs.createReadStream(path).on('data', (chunk) => { console.log(bytes += chunk.length, size); }) }); 个字节,读取/排出过程以迭代方式运行。

65536node v4.5.0来说,这似乎很有效。

答案 2 :(得分:1)

var request = require('request');
    var fs = require('fs');  
    let path ="C:/path/to/file";
    var formData = {
        vyapardb: fs.createReadStream(path)
    };

    let size = fs.lstatSync(path).size;

    var headers = {
        'Accept' : 'application/json',
        'Authorization' : 'Bearer '+token,
    };

    var r = request.post({url:'http://35.12.13/file/upload', formData: formData,  headers: headers}, function optionalCallback(err, httpResponse, body) {
        clearInterval(q);

    });
    var q = setInterval(function () {
        var dispatched = r.req.connection._bytesDispatched;
        let percent = dispatched*100/size;
         console.dir("Uploaded: " + percent + "%");

    }, 250);
}

答案 3 :(得分:0)

我知道这很旧,但是我只是找到了一个库“ progress-stream”,这个库没有被提及,并且做得很好。 https://www.npmjs.com/package/progress-stream

const streamProg = require('progress-stream');
const fs = require('fs');
const request = require('request');

const myFile = 'path/to/file.txt';
const fileSize = fs.statSync('path/to/file.txt').size;
const readStream = fs.createReadStream(myFile);
const progress = streamProg({time: 1000, length: fileSize})
    .on('progress', state => console.log(state));

readStream.pipe(progress).pipe(request.put({url: 'SOMEURL/file.txt'}));

类似地,它也可以在下载的管道之间使用。

答案 4 :(得分:-1)

有人创建了一个很好的模块来实现这一目标,该模块已经在transloadit的生产堆栈中运行(因此它可靠且维护良好)。你可以在这里找到它:

https://github.com/felixge/node-formidable

代码应如下所示:

var formidable = require('formidable'),
    http = require('http'),

    util = require('util');

http.createServer(function(req, res) {
  if (req.url == '/upload' && req.method.toLowerCase() == 'post') {
    // parse a file upload
    var form = new formidable.IncomingForm();
    form.parse(req, function(err, fields, files) {
      res.writeHead(200, {'content-type': 'text/plain'});
      res.write('received upload:\n\n');
      res.end(util.inspect({fields: fields, files: files}));
    });
    return;
  }

  // show a file upload form
  res.writeHead(200, {'content-type': 'text/html'});
  res.end(
    '<form action="/upload" enctype="multipart/form-data" method="post">'+
    '<input type="text" name="title"><br>'+
    '<input type="file" name="upload" multiple="multiple"><br>'+
    '<input type="submit" value="Upload">'+
    '</form>'
  );
}).listen(80);

然后,您可以使用Socket.io

将状态推送到客户端

有趣的注意:这是导致Node创建的问题之一。在this video Ryan谈到节点是如何开始尝试找到通知用户的最佳方式,实时,关于通过网络上传文件的状态...无论如何我离题,但视频值得观看如果您对Node的历史感兴趣