Prateek Kumar
Prateek Kumar

Reputation: 21

AWS SDK JavaScript Promise with callback httpUploadProgress

I am trying to get the httpUploadProgress using AWS S3 SDK JavaScript. Using this lines I am able to see the expected result with the upload progress, but how to get the same using Promise(), I am using this in browser as external JS resource.

Working example:

    function uploadFile(){
        var bucket = new AWS.S3({params: {Bucket: BUCKET_NAME}});
        var fileChooser = document.getElementById('file');
        var file = fileChooser.files[0];
        if (file) {
            console.log();
            var opts = {queueSize: 1, partSize: 1024 * 1024 * 5};
            var params = {Key: file.name, ContentType: file.type, Body: file};
            s3.upload(params,opts).on('httpUploadProgress', function(evt) {
            console.log("Uploaded :: " + parseInt((evt.loaded * 100) / evt.total)+'%');
            }).send(function(err, data) {
                console.log(err);
                alert("File uploaded successfully.");
            });
        }
        return false;
    }

Same I want with the promises.

function uploadFile(){
        var bucket = new AWS.S3({params: {Bucket: BUCKET_NAME}});
        var fileChooser = document.getElementById('file');
        var file = fileChooser.files[0];
        if (file) {
            console.log();
            var opts = {queueSize: 1, partSize: 1024 * 1024 * 5};
            var params = {Key: file.name, ContentType: file.type, Body: file};
            var promise = s3.upload(params,opts).promise();
            promise()
               .then(function(data){}, function(error){})
        }
        return false;
    }

Upvotes: 2

Views: 4673

Answers (1)

Richard Wattie
Richard Wattie

Reputation: 61

I had the same problem. I'm not sure on your implemenatation of it but I think this is what you might be looking for...

function async uploadFile(){
  var bucket = new AWS.S3({params: {Bucket: BUCKET_NAME}});
  var fileChooser = document.getElementById('file');
  var file = fileChooser.files[0];

  if (file) {
    console.log();
    var opts = {queueSize: 1, partSize: 1024 * 1024 * 5};
    var params = {Key: file.name, ContentType: file.type, Body: file};

    var upload = s3.upload(params,opts)
        .on('httpUploadProgress', function(evt) {
          console.log("Uploaded :: " + parseInt((evt.loaded * 100) / evt.total)+'%');
        })
        .promise();

    await upload.then(function(err, data) {
      console.log(err);
      alert("File uploaded successfully.");
    });
  }

  return false;
}

Upvotes: 5

Related Questions