Multiple Images Upload to Amazon S3 using PHP & jQuery

I am going to explain jQuery Multiple File upload to Amazon S3 bucket without refreshing a page using PHP & jQuery. Most of the social networking sites are storing files/images in Amazon servers only. Let me explain why do we need Amazon S3

Amazon S3 (Simple Storage Service) is an online service provided by Amazon.com, that allows web designers to store large amounts of data online. Amazon has also built the S3 service to be very reliable, and guarantees server uptime of 99.99%.

There are so many tools are available to upload files to Amazon S3 server like Amazon S3Fox

Advantages of storing files in Amazon S3 over server hard disk

  • Storage Cost is very less
  • Data retrival is very fast
  • Data stored in Amazon Cloud
  • More Private

Now we are going to see jQuery multiple file upload to S3 with PHP

jQuery Multiple File UPload

We need Amazon AWS Access key & Secret Key to upload filesSo Login to Amazon account and click here to get AWS Access Credentials.

Create Access Credentials in Amazon S3
Create Access Credentials in Amazon S3

After login to Amazon account – you have to create a Bucket & assign a permission to Everyone to Read in Properties Tab

Bucket Permission in Amazon S3

Once created, You have to provide Amazon Key details in config.php

Contents

Config.php

//Bucket Name
$bucket_name ="your bucket name";

//include the S3 class
if (!class_exists('S3'))require_once('S3.php');

//AWS access informations
if (!defined('awsAccessKey')) define('awsAccessKey', 'access key');
if (!defined('awsSecretKey')) define('awsSecretKey', 'secret key');

//instantiate the s3 class
$s3 = new S3(awsAccessKey, awsSecretKey);

//this is used to create a bucket in amazon S3
$s3->putBucket($bucket_name, S3::ACL_PUBLIC_READ);

You can modify the permissions easily by replacing with below code

  • ACL_PRIVATE
  • ACL_PUBLIC_READ
  • ACL_PUBLIC_READ_WRITE
  • ACL_AUTHENTICATED_READ – used to create presigned object url for authenticated access

Upload.php

if(isset($_POST) && !empty($_FILES) && !empty($_FILES['uploadfile']['name'])) {

//upload file formats
$valid_file_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP");

function get_file_extension($file_name) {
return substr(strrchr($file_name,'.'),1);
}

$filename = $_FILES['uploadfile']['name'];
$tmp_filename = $_FILES['uploadfile']['tmp_name'];
$filetype = strtolower($_FILES['uploadfile']['type']);
//get file extenstion to verify the format
$extension = get_file_extension($filename);

if(in_array($extension,$valid_file_formats))
{
//include config.php
include_once "config.php";

//set content type in headers inorder to display image in browser
$header = array('Content-Type' => $filetype);

//change filename
$new_file_name = "w3_".time().".".$extension;
if($s3->putObject(S3::inputFile($tmp_filename), $bucket_name , $new_file_name, S3::ACL_PUBLIC_READ, array(), $header) )
{
$img = "http://".$bucket_name.".s3.amazonaws.com/".$new_file_name;
echo "1-".$img;
} else {
echo "2-Upload Failed";
}
} else {
echo "3-Not a Valid Format";
}
} else {
echo "4-Please Select a File";
}

jQuery Code

jQuery(document).ready(function(){
var btnUpload=jQuery('#upload_pic');
var status=jQuery('#statuss');
new AjaxUpload(btnUpload, {
action: 'upload.php',
name: 'uploadfile',
onSubmit: function(file, ext){
if (! (ext && /^(jpg|jpeg|gif|png)$/.test(ext))){
// extension is not allowed
status.text('Only JPG or GIF or PNG files are allowed');
return false;
}
status.text('Uploading...');
},
onComplete: function(file, response){
//On completion clear the status
status.text('');
//split the response
var resp = response.split('-');
//Add uploaded file to list
if(resp[0] == 1){
//store image
var img = resp[1];
var apic = jQuery('#imgs').val();
//uploaded images are stored in hidden text box for future reference
jQuery('#imgs').val(img+','+apic);
jQuery('#files').append('<img src="'+img+'" height="150" width="150">');
} else {
jQuery('#files').text(resp[1]).addClass('error');
}
}
});
});

Please don’t forget to share and subscribe to latest updates of the blog. Also any comments and feedback are all welcome!

Thanks!

You May Also Like

Never Miss Any Web Tutorials, Guides, Tips and Free eBooks

Join Our Community Of 50,000+ Web Lovers and get a weekly newsletter in your inbox

 

I hate spam too. Unsubscribe at any time.

16 thoughts on “Multiple Images Upload to Amazon S3 using PHP & jQuery”

  1. This example doesn’t even give the option to select multiple file.How this example achieve multiple file upload in Amazon S3

    Reply
  2. Hi, it a good script.
    i just need to know how can we upload the file (xyz.jpg) within folder of bucket (eg. bucket_name/images),

    Reply
  3. Hi, I am new to PHP and JS, It looks like it is for one image upload, I want to upload multiple files to amazon s3 and get back their path in order to update in db kindly give me an idea

    Reply
      • ThanQ for your quick reply.
        My scenario is to upload multiple files to s3 all in a single shot and get back their url for some work later, will php alone can upload multiple files or js is required i am something like fileuploader or blueimp for multiple files upload but these are too complex understand and work with

        Reply
      • ThanQ for your quick reply.
        My scenario is to upload multiple files to s3 all in a single shot and get back their url for some work later, will php alone can upload multiple files or js is required i am something like fileuploader or blueimp for multiple files upload but these are too complex understand and work with

        Reply
  4. Realy nice, thats helps me a lot!

    But i have a problem, is it possible to get a file also from an url? I need to upload a lot of images to the s3 storage and it would be nice to write a script, which get the files directly from an external url without the roundabout way on my server…. ??

    Reply

Leave a Comment