Saturday 20 September 2014

Upload image to Amazon S3 server using AWS JavaScript and display the progress bar.

I will explain how to upload the image to Amazon S3 server using AWS JavaScript SDK and display the progress bar.

Prerequisite as follows
1) To Upload the image to S3 server, we need the AWS SDK script file.
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.0.16.min.js"></script>

Please find the below URL to get the latest JavaScript SDK version and include the script file accordingly from the below URL.
https://aws.amazon.com/releasenotes/JavaScript?browse=1

2) To update the progress bar included the bootstrap CSS.
Please find the below URL to get the bootstrap CSS.
http://getbootstrap.com/css/

I assume that the AWS library is loaded, configured, and authenticated with the correct credentials.

Select the Image:
<input id="fileUpload" name="fileUpload" type="file" /> <br />
<div class="text-center progress progress-striped div-display">
<div class="progress-bar progress-bar-success" id="progress">
</div>
</div>
<br />
<input id="btnSubmit" type="button" value="Upload the Image" class="btn btn-primary" /> <br />
<div id="results"></div>

<script type="text/javascript">

$(document).ready(function () {

$('#btnSubmit').click(function () {
var accessKey = ''; //Provide the Amazon access key
var secretKey = ''; //Provide the Amazon secret access key
var region = ''; //Specify the Amazon region
var bucketName = ''; //Provide the Amazon bucket Name

AWS.config.update({ accessKeyId: accessKey, secretAccessKey: secretKey });
    AWS.config.region = region;

var fileChooser = document.getElementById('fileUpload');
var file = fileChooser.files[0];

if (file) {
results.innerHTML = '';

var bucket = new AWS.S3({ params: { Bucket: bucketName } });
var params = {Key: file.name, ContentType: file.type, Body: file};
var request = bucket.putObject(params, function (err, data) {
results.innerHTML = err ? 'ERROR!' : 'UPLOADED.';
});

request.on('httpUploadProgress', function (progress) {
var uploadedSize = progress.loaded; //Get the uploaded image size
var totalSize = progress.total;     //Get the total image size
var percentage = (uploadedSize / totalSize) * 100;
                               //Provide the percentage to the progress bar
$('#progress').css({ "width": percentage + "%" });
});
}
else {
results.innerHTML = 'Nothing to upload.';
}
});
});
</script>

This article will give basic idea how to upload the image using JavaScript to Amazon S3 server and update the progress bar.

Please provide your valuable suggestions and comments.

No comments:

Post a Comment