Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to actually track S3 upload progress (JavaScript SDK)

I'd like to be able to track an S3 file upload's progress (bytes uploaded out of bytes total).

Before anyone flags this as a dupe—it's not. Every other answer I've seen on StackOverflow is actually incorrect. If you do something like this:

s3
  .putObject(
    {
      Bucket: 'xyz',
      Key: 'wow.png',
      Body: data,
    },
    (err, data) => {
      console.log('done', err, data);
    }
  )
  .on('httpUploadProgress', progress => {
    console.log('Progress:', progress);
  });

You get a single progress update, showing the total size:

Progress { loaded: 1082019, total: 1082019 }

This is not useful. What I'm looking for is a more fine-grained report of upload progress like you would normally see during an upload (no matter the file size.. 1MB or 100MB):

0% out of 100%
3% out of 100%
7% out of 100%
9% out of 100%
(etc)

like image 720
ffxsam Avatar asked Feb 22 '18 02:02

ffxsam


2 Answers

Well, this is the answer (as lame as it is). Just sharing this as it could be a potential gotcha for other people.

This will not work in a Node.js environment! I've been testing this in that manner, and it just calls the httpUploadProgress callback once. Once I moved my code to an actual front-end client, it works as expected and prints the progress as the file uploads.

like image 146
ffxsam Avatar answered Sep 22 '22 01:09

ffxsam


Try this:

s3
.putObject({
        Bucket: 'xyz',
        Key: 'wow.png',
        Body: data,
    },
    (err, data) => {
        console.log('done', err, data);
    }
)
.on('httpUploadProgress', ({ loaded, total }) => {
    console.log(ContentType, 'Progress:', loaded, '/', total, `${Math.round(100 * loaded / total)}%`);
})
like image 22
Rafael Avatar answered Sep 22 '22 01:09

Rafael