AWS S3 file upload with progress bar using javascript sdk

17 / Jun / 2015 by Deepak Kumar Mittal 6 comments

You can upload files on AWS S3 using a server side solution, but in case of larger files it is advisable to use a client side solution. You can probably use JavaScript file upload feature of AWS S3. This is simple three step feature as described below:

Step 1 : In the head section of your page include javascript sdk and specify your keys like this:

<script src="https://sdk.amazonaws.com/js/aws-sdk-2.1.24.min.js"></script>
<script type="text/javascript">
    AWS.config.update({
        accessKeyId : 'ACCESS_KEY',
        secretAccessKey : 'SECRET_KEY'
    });
    AWS.config.region = 'AWS_REGION';
</script>

Step 2 : Now create a simple html form with a file input.

<form id="fileUploadForm" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" value="dataFile" required="">
</form>

Step 3 : Now upload your input file to S3

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

To upload the file successfully, you need to enable CORS configuration on S3.

Generally, it is not advisable to display your keys directly on page, so you can use Amazon Cognito or web identity federation feature.

Know more 

Tag -

FOUND THIS USEFUL? SHARE IT

comments (6)

  1. usama

    Can you please guide us a little on how we can get these Amazon Cognito or web identity federation feature.
    Thanks for awesome tutorial.

    Reply
  2. tarun singh

    How can I upload 100GB AEM package using AWS s3 ? I am getting errors as the internal division of the package is exceeding the part-limits. And also, if you can tell me how to change that upload part-limit?

    Reply
  3. Thor

    “Step 1: Put your SECRET ACCESS KEY in the header of your client-side file, for the world to see! What could go wrong?”

    Reply
    1. Sebastien Lemieux

      Nothing. AWS good practices are to create restricted users for those operations. Having a user who can only upload to a specific S3 bucket won’t be a problem.

      Reply

Leave a comment -