As we have covered this tutorial with live demo to upload files to Amazon s3 server with JavaScript, so the file structure for this example is following.
- index.php
- aws_config.js
- s3_upload.js
Steps1: Create Amazon S3 Account
First we need to create Amazon S3 account and get your bucket name and access keys to use for uploading files.
Steps2: Configure S3 Details
After getting Amazone S3 account details, we will define Amazon S3 account details in aws_config.js with access key and secret key.
AWS.config.update({
accessKeyId : 'ACCESS_KEY',
secretAccessKey : 'SECRET_KEY'
});
AWS.config.region = 'YOUR REGION';
Steps3: Include jQuery and JavaScript AWS SDK
In index.php file, we will need to include Amazon JavaScript SDK to handle file upload to S3 server with JavaScript. We will also include aws_config.js and s3_upload.js to handle file upload to Amazon S3 server.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.1.24.min.js"></script>
<script src="aws_config.js"></script>
<script src="s3_upload.js"></script>
Steps4: Create File Upload Form
In index.php file, we will create HTML Form to browse file to upload with upload button.
<form id="uploadForm" method='post' enctype="multipart/form-data">
<h3>Upload File</h3><br/>
<input type='file' name="upFile" id="upFile" required="" />
<br>
<input type='submit' value='Upload'/>
</form>
Steps5: Handle File Upload Amazon S3 Server with JavaScript
Now finally in s3_upload.js file, we will handle functionality to upload files by creating AWS S3 object with BUCKET NAME and then upload files using AWS upload method.
$( document ).ready(function() {
$("#uploadForm").submit(function() {
var bucket = new AWS.S3({params: {Bucket: 'YOUR BUCKET_NAME'}});
var uploadFiles = $('#upFile')[0];
var upFile = uploadFiles.files[0];
if (upFile) {
var uploadParams = {Key: upFile.name, ContentType: upFile.type, Body: upFile};
bucket.upload(uploadParams).on('httpUploadProgress', function(evt) {
}).send(function(err, data) {
$('#upFile').val(null);
$("#showMessage").show();
});
}
return false;
});
});
You can view the live demo from the Demo link and can download the script from the Download link below.
Demo[sociallocker] Download[/sociallocker]