Upload file directly to Amazon S3 using PHP + Ajax + Jquery + blueimp

If you are uploading file to your server and then moving to Amazon S3 then you can choose ‘direct upload to Amazon S3’ option for your application to replace two steps to one. Also, one advantage of this is uploading directly to Amazon S3 will be faster as Amazon S3 will have enough bandwidth to take file.

If you are looking for direct posting file by submitting form then you can follow steps given in Amazon AWS article “Browser Uploads to S3 using HTML POST Forms” but if you like to upload file without refreshing page using Ajax and Bluimp plugin there here is the code for this.

To implement this functionality, first of all, you have to add CORS configuration to Amazon S3 bucket.

<CORSConfiguration>
 <CORSRule>
   <AllowedOrigin>http://www.example.com</AllowedOrigin>

   <AllowedMethod>PUT</AllowedMethod>
   <AllowedMethod>POST</AllowedMethod>
   <AllowedMethod>DELETE</AllowedMethod>

   <AllowedHeader>*</AllowedHeader>
 </CORSRule>
 <CORSRule>
   <AllowedOrigin>*</AllowedOrigin>
   <AllowedMethod>GET</AllowedMethod>
 </CORSRule>
</CORSConfiguration>

You need to download Jquery and blueimp for this plugin.

http://blueimp.github.io/jQuery-File-Upload/


<?php

$bucket = "s3.triotips.com";
 $accesskey = "AKIAILSadOUXCX6TU7IEVA";
 $secret = "JmCr3d1W4ZI/BzwOjAFk0AbvNgrk37FtlqxVH";

function getS3Policy()
 {
 $now = strtotime(date("Y-m-d\TG:i:s"));
 $expire = date('Y-m-d\TG:i:s\Z', strtotime('+30 minutes', $now));
 $policy='{
 "expiration": "' . $expire . '",
 "conditions": [
 {
 "bucket": "s3.triotips.com"
 },
 {
 "acl": "public-read"
 },
 [
 "starts-with",
 "any",
 ""
 ],
 {
 "success_action_status": "201"
 },
 [
 "starts-with",
 "$key",
 ""
 ]
 ]
 }';
 return $policy;
 }

/*
 * Calculate HMAC-SHA1 according to RFC2104
 * See http://www.faqs.org/rfcs/rfc2104.html
 */
 function hmacsha1($key,$data) {
 $blocksize=64;
 $hashfunc='sha1';
 if (strlen($key)>$blocksize)
 $key=pack('H*', $hashfunc($key));
 $key=str_pad($key,$blocksize,chr(0x00));
 $ipad=str_repeat(chr(0x36),$blocksize);
 $opad=str_repeat(chr(0x5c),$blocksize);
 $hmac = pack(
 'H*',$hashfunc(
 ($key^$opad).pack(
 'H*',$hashfunc(
 ($key^$ipad).$data

)
 )
 )
 );
 return bin2hex($hmac);
 }

/*
 * Used to encode a field for Amazon Auth
 * (taken from the Amazon S3 PHP example library)
 */
 function hex2b64($str)
 {
 $raw = '';
 for ($i=0; $i < strlen($str); $i+=2)
 {
 $raw .= chr(hexdec(substr($str, $i, 2)));
 }
 return base64_encode($raw);
 }

$base64Policy = base64_encode(getS3Policy());
 $signature = hex2b64(hmacsha1($secret, $base64Policy));

?>

Upload file direct to Amazon S3 – Triotips.com

 





Upload file :








 <script>
 $(document).ready( function() {

var ellipsisCount = 1;
 var name = '';
 var hashName = '';

$('.direct-upload').each( function() {

var form = $(this);

$(this).fileupload({
 url: form.attr('action'),
 type: 'POST',
 autoUpload: true,
 add: function (event, data) {

// Use XHR, fallback to iframe
 options = $(this).fileupload('option');
 use_xhr = !options.forceIframeTransport &&
 ((!options.multipart && $.support.xhrFileUpload) ||
 $.support.xhrFormDataFileUpload);

if (!use_xhr) {
 alert('here');
 using_iframe_transport = true;
 }
 // Message on unLoad.
 window.onbeforeunload = function() {
 alert('You have unsaved changes.');
 return 'You have unsaved changes.';
 };
 var currentdate = new Date();
 var datetime = "Start time: " + currentdate.getDay() + "/"+currentdate.getMonth()
 + "/" + currentdate.getFullYear() + " @ "
 + currentdate.getHours() + ":"
 + currentdate.getMinutes() + ":" + currentdate.getSeconds();
 $('.log').append("<BR>"+datetime);
 // Submit
 data.submit();
 },
 send: function(e, data) {

},
 progress: function(e, data){
 // This is what makes everything really cool, thanks to that callback
 // you can now update the progress bar based on the upload progress
 var percent = Math.round((e.loaded / e.total) * 100);
 var percentTemp = $('#percentTemp').val();
 if(percent > percentTemp) {
 $('#percentTemp').val(percent);
 if(percentTemp % 10 == 0) {
 var currentdate = new Date();
 var datetime = currentdate.getDay() + "/"+currentdate.getMonth()
 + "/" + currentdate.getFullYear() + " @ "
 + currentdate.getHours() + ":"
 + currentdate.getMinutes() + ":" + currentdate.getSeconds();
 $('.log').append("<BR>"+percentTemp + '% ('+e.loaded/1000000+'MB of '+e.total/1000000+'MB) at time : '+datetime);
 }
 }

$('.bar').css('width', percent + '%');
 $('.bar').html(percent + '%');

},
 fail: function(e, data) {
 window.onbeforeunload = null;
 },
 success: function(data) {
 // Here we get the file url on s3 in an xml doc
 var url = $(data).find('Location').text()
 var currentdate = new Date();
 var datetime = "Complete time: " + currentdate.getDay() + "/"+currentdate.getMonth()
 + "/" + currentdate.getFullYear() + " @ "
 + currentdate.getHours() + ":"
 + currentdate.getMinutes() + ":" + currentdate.getSeconds();
 $('.log').append("<BR>"+datetime);
 $('.log').append("<BR>"+url);
 $('#real_file_url').val(url) // Update the real input in the other form
 },
 done: function (event, data) {

},
 });
 });

});
 </script>

</body>
</html>

Chetan Patel

Chetan Patel is blogger, writes on Tech News, current trends, Gadgets Reviews, Website owner guide and Tips. You can connect him at Google+ & Facebook.