简体   繁体   中英

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)

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM