Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload Progress — Request

I'm uploading a file using Request.

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

How do I know how much data has actually been uploaded? Is there some event that I can subscribe to or is there a property of the request that I can poll?

If none, what would be the best approach to upload data and know how much has been uploaded?

like image 277
Gautham Badhrinathan Avatar asked Aug 23 '12 19:08

Gautham Badhrinathan


People also ask

What is Uploadprogress?

A PHP extension to track progress of a file upload, including details on the speed of the upload, estimated time remaining, and access to the contents of the file as it is being uploaded.

How do I upload a file using XMLHttpRequest?

Create the form object for submissionCreate form data that would be submitted in the POST request to /upload. The formData will contain the file object which can be easily appended. Then an AJAX request can be created by using XMLHttpRequest() method.

Which PHP INI directive defines how often the session upload progress information should be updated?

upload_progress. min_freq INI options control how frequent the upload progress information should be recalculated.


2 Answers

I spent a couple of hours to find anything valid in request and node sources, and finally found a different approach, which feels more correct to me.

We can rely on drain event and bytesWritten property:

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

Alternatively if you need to handle progress of file bytes, it's easier to use stream data event:

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);
  })
});

Stream buffer size is 65536 bytes and read/drain procedure runs iteratively.

This seems to be working pretty well for me with node v4.5.0 and request v2.74.0.

like image 64
VisioN Avatar answered Sep 24 '22 00:09

VisioN


I needed a handle on the upload progress for yet another project of mine.

What I found out is that you can poll the request's connection._bytesDispatched property.

For example:

r = request.post url: "http://foo.com", body: fileAsBuffer
setInterval (-> console.log "Uploaded: #{r.req.connection._bytesDispatched}"), 250

Note: If you were piping to r, poll r.req.connection.socket._bytesDispatched instead.

like image 26
Gautham Badhrinathan Avatar answered Sep 23 '22 00:09

Gautham Badhrinathan