简体   繁体   中英

AWS SDK JavaScript: how display upload progress of AWS.S3.putObject?

I'm developing a JavaScript client to upload files directly to Amazon S3.

<input type="file" id="file-chooser" /> 
<button id="upload-button">Upload to S3</button>
<div id="results"></div>

<script type="text/javascript">
  var bucket = new AWS.S3({params: {Bucket: 'myBucket'}});

  var fileChooser = document.getElementById('file-chooser');
  var button = document.getElementById('upload-button');
  var results = document.getElementById('results');
  button.addEventListener('click', function() {
    var file = fileChooser.files[0];
    if (file) {
      results.innerHTML = '';

      var params = {Key: file.name, ContentType: file.type, Body: file};
      bucket.putObject(params, function (err, data) {
        results.innerHTML = err ? 'ERROR!' : 'UPLOADED.';
      });
    } else {
      results.innerHTML = 'Nothing to upload.';
    }
  }, false);
</script>

The example from Amazon documentation works fine, but it doesn't provide any feedback on the upload progress.

Any ideas?

Thanks

Changing my Google query I Found what I needed:

https://github.com/aws/aws-sdk-js/commit/084f676927b9cd3da337bd6d0d230680c138d73b

Documentation example should have it...

Rather than using the s3.PutObject function why not instead use the ManagedUpload function.

It has been specifically developed to allow you to hook into a httpUploadProgress event that should allow the updating of your progress bar to be implemented fairly easily.

I have done some customisation for file upload progress. Use this same logic in node, angular and javascript.

Here is repository link :

https://github.com/aviboy2006/aws-s3-file-upload-progress

Use this fiddle for test: https://jsfiddle.net/sga3o1h5/

Note : Update access key, bucketname and secret key.

 var bucket = new AWS.S3({
   accessKeyId: "",
   secretAccessKey: "",
   region: 'us-east-1'
 });

 uploadfile = function(fileName, file, folderName) {
   const params = {
     Bucket: "fileuploadprocess",
     Key: folderName + fileName,
     Body: file,
     ContentType: file.type
   };
   return this.bucket.upload(params, function(err, data) {

     if (err) {
       console.log('There was an error uploading your file: ', err);
       return false;
     }
     console.log('Successfully uploaded file.', data);
     return true;
   });
 }

 uploadSampleFile = function() {
   var progressDiv = document.getElementById("myProgress");
   progressDiv.style.display="block";
   var progressBar = document.getElementById("myBar");
   file = document.getElementById("myFile").files[0];
   folderName = "Document/";
   uniqueFileName = 'SampleFile'; 
   let fileUpload = {
     id: "",
     name: file.name,
     nameUpload: uniqueFileName,
     size: file.size,
     type: "",
     timeReference: 'Unknown',
     progressStatus: 0,
     displayName: file.name,
     status: 'Uploading..',
   }
   uploadfile(uniqueFileName, file, folderName)
     .on('httpUploadProgress', function(progress) {
       let progressPercentage = Math.round(progress.loaded / progress.total * 100);
       console.log(progressPercentage);
       progressBar.style.width = progressPercentage + "%";
       if (progressPercentage < 100) {
         fileUpload.progressStatus = progressPercentage;

       } else if (progressPercentage == 100) {
         fileUpload.progressStatus = progressPercentage;

         fileUpload.status = "Uploaded";
       }
     })
 }

I bumped into this post, then i found this AWS npm package, which does exactly what you are asking for: @aws-sdk/lib-storage

import { Upload } from "@aws-sdk/lib-storage";
import { S3Client, S3 } from "@aws-sdk/client-s3";

const target = { Bucket, Key, Body };
try {
  const parallelUploads3 = new Upload({
    client: new S3({}) || new S3Client({}),
    tags: [...], // optional tags
    queueSize: 4, // optional concurrency configuration
    partSize: 5MB, // optional size of each part
    leavePartsOnError: false, // optional manually handle dropped parts
    params: target,
  });

  parallelUploads3.on("httpUploadProgress", (progress) => {
    console.log(progress);
  });

  await parallelUploads3.done();
} catch (e) {
  console.log(e);
}

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