AWS S3 file upload with progress bar using javascript sdk

17 / Jun / 2015 by Deepak Kumar Mittal 1 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 (1 “AWS S3 file upload with progress bar using javascript sdk”)

Leave a comment -