Amazon S3

Upload to Amazon S3 using Javascript with progress bar


Amazon S3 can be integrated with Salesforce using the JavaScript SDK which enables you to use Amazon Services. To start using JavaScript SDK you need only a script tag.
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.1.24.min.js"></script>

To allow DML operation on the S3 bucket make sure the CORS configuration is updated as mentioned below :

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <CORSRule>
        <AllowedOrigin>*</AllowedOrigin>
        <AllowedMethod>PUT</AllowedMethod>
        <AllowedMethod>POST</AllowedMethod>
        <AllowedMethod>GET</AllowedMethod>
        <AllowedMethod>HEAD</AllowedMethod>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
<AllowedHeader>*</AllowedHeader>
    </CORSRule>
</CORSConfiguration>


Once the CORS are defined you are set and can use the below code directly into your Visualforce page.
Remember to replace the Text in Red below with your credentials.

<apex:page docType="html-5.0" sidebar="false" showHeader="false" showChat="false" showQuickActionVfHeader="false" standardStylesheets="false" setup="false">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"/><style>
form {
  padding: 20px;
  border: 1px solid #cccccc;
  border-radius: 10px;
  -moz-border-radius: 10px;
  -webkit-box-shadow: 0 0 10px #ccc;
  -moz-box-shadow: 0 0 10px #ccc;
  box-shadow: 0 0 10px #ccc;
  background-image: -moz-linear-gradient(top, #ffffff, #f2f2f2);
  background-image: -webkit-gradient(linear, left top, left bottom, from(#ffffff), to(#f2f2f2));
}

#mainContent {
  width: 640px;
  float: left;
  margin-left: 330px;
  overflow: hidden;
  padding-top: 155px;
}

h4.fileToUpload {
  margin-top: 0.0em;
  font-size: 16pt;
}

h1, h2, h3, h4, h5, h6 {
  color: #7F3300;
  margin-top: 1.5em;
  margin-bottom: 0.3em;
  font-family: DaxCompact-RegularRegular, Georgia, Helvetica, Times, 'Times New Roman' , serif;
}
.row {
  padding-bottom: 5px;
}
input {
  border: 1px solid #ccc;
  font-size: 16px;
  padding: 5px 10px 5px 10px;
  border-radius: 10px;
  -moz-border-radius: 10px;
  -webkit-transition: all 0.5s ease-in-out;
  -moz-transition: all 0.5s ease-in-out;
  transition: all 0.5s ease-in-out;
}

input[type=submit]{
  opacity: 1.0;
  background-image: -moz-linear-gradient(top, #ffffff, #dfdfdf);
  background-image: -webkit-gradient(linear, left top, left bottom, from(#ffffff), to(#dfdfdf));
  cursor: pointer;
}

</style>
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
     <script src="https://sdk.amazonaws.com/js/aws-sdk-2.1.12.min.js"></script>


     <div id ="mainContent">
     <form action="#"  method="post" enctype="multipart/form-data" id="uploadForm">
        <h4 class="fileToUpload">Select a File to Upload in AWS</h4><br />
        <div class="row">
              <input type="file" size="50" name="file" id="file" onchange="fileSelected();" />
        </div>
        <div class="row">
          <input type="submit" value="Upload"  id="btn_submit" />
        </div>
       <div class="progress">
            <div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"  id="Upload1" style="width:0%">
                <span class="sr-only">20% Complete</span>
            </div>
       </div>
    </form>
    </div>
 
 

<!-- Aws S3 Upload code -->
<script>
       
     
         AWS.config.update(
      {
        accessKeyId: "YOUR AWS ACCESS KEY ID",
        secretAccessKey: "YOUR AWS SECRET ACCESS KEY",
        region_config: "eu-west-1"
      }
     );

$("#btn_submit").click(function(event) {
    event.preventDefault();
    var bucket = new AWS.S3({params: {Bucket: 'AWS 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)+'%');
            var per=parseInt((evt.loaded * 100) / evt.total)+'%';
            document.getElementById("Upload1").style.width=per ;
     
        }).send(function(err, data) {
         
            if(!err) {
               alert("File uploaded Successfully");
            }                              
             
            });
    }
        return false;
    });
</script>
<!-- Aws S3 upload ends -->

</apex:page> 


Click here to View post for  Download Document from S3 Using JavaScript


Hope you found this useful, if you have any question don't hesitate to mention them in comments!!

About Saurabh Dua

3 comments:

  1. is there any size limits for upload and downloads to S3?

    ReplyDelete
  2. In this example you hardcoded credentials in your script, which is not a good practise: http://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials-browser.html

    ReplyDelete
  3. This is not working at my end !!

    ReplyDelete

Note: only a member of this blog may post a comment.

Powered by Blogger.