AWS S3 file upload with progress bar using javascript sdk

17 / Jun / 2015 by Deepak Kumar Mittal 11 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:

[code]
<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>
[/code]

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

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

Step 3 : Now upload your input file to S3

[code]
$("#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;
});
[/code]

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 

FOUND THIS USEFUL? SHARE IT

comments (11)

  1. Kumar

    Hello, Can this handle large file upload. from my testing it’s not uploading any larger file.is there any possibility to handle large file upload using this ?

    Reply
  2. 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
  3. 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
  4. 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
    2. YouShouldKnowBetter

      Why would it matter? if you set up your S3 correctly then only certain domains can do anything with the bucket.

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *