Build an uploader for S3

S3 is Amazon’s “Simple Storage Service” for hosting content on the web. It allows developers to offload static content to their powerful content delivery network at low cost, to improve site performance. I’ve used S3 on a number of projects to host content, but one thing that only recently cropped up wad the notion of allowing users to upload their own content to the service from within any given site. To accomplish this I had to use a little bit of everything, including PHP and jQuery. But don’t worry, if you don’t want to use jQuery, this technique should still apply to other implementations.

As I said we will be using jQuery for this, and more specifically, the fantastic plugin Uplodify – a set of files that will enable simple uploading, and that will handle all the heavy lifting of file manipulation. So go ahead and download/unzip Uplodify, and then stick it on your server. I then used the following standard HTML to display the upload button.

<div id="upload_box">
	<div id="file_upload" name="theFile"></div>
</div>

Having done that, make sure to include jQuery, swifobject.js, and jquery.uplodify.[VERSION].js, and then add the following JS.

<script type="text/javascript">
    $(document).ready(function() {
      $('#file_upload').uploadify({
        'uploader'  : 'uploadify.swf',
        'script'    : 'uploadify.php',
        'folder'    : 'uploads',
        'multi'	: true,
        'fileExt'   : '*.jpg;*.gif;*.png',
        'auto'      : true,
        'buttonImg' : 'button.jpg',
        'width'	: '86',
        'height'	: '28',
        'onSWFReady': function(){ $("#file_upload").show(); },
      });
      
    });
</script>

And that’s the basic configuration needed to get Uploadify working. Now we need to enlist the help of a PHP class to enable us to interface with S3. That class allows you to do some pretty advanced stuff, and is a great solution all round for working with S3. In our case you just need to download that that and pop it in the same directory as the file uplodify.php.

And now we are finally ready to add the functionality that we’ve all been waiting for. Open uplodify.php and change:

move_uploaded_file($tempFile,$targetFile);
echo str_replace($_SERVER['DOCUMENT_ROOT'],'',$targetFile);

to:

$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
$targetFile =  str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];

 $fileTypes  = str_replace('*.','',$_REQUEST['fileext']);
 $fileTypes  = str_replace(';','|',$fileTypes);
 $typesArray = split('\|',$fileTypes);
 $fileParts  = pathinfo($_FILES['Filedata']['name']);

 if (in_array($fileParts['extension'],$typesArray)) {
	
	if (!class_exists('S3'))require_once('S3.php');
	
	//AWS access info
	if (!defined('awsAccessKey')) define('awsAccessKey', '[ACCESS KEY]');
	if (!defined('awsSecretKey')) define('awsSecretKey', '[SECRET KEY]');
	
	//instantiate the class
	$s3 = new S3(awsAccessKey, awsSecretKey);

	//move the file
	$s3->putObject($_FILES['Filedata']['tmp_name'], "[BUCKET NAME]", $_FILES['Filedata']['name'], S3::ACL_PUBLIC_READ);


	echo "http://s3.amazonaws.com/[BUCKET NAME]/".$fileName;
 } else {
 	echo 'Invalid file type.';
 }

So what we’ve done there is replaced the part of the code that previously moved the uploaded file (with the imaginatively named move_uploaded_file() function), with some code to invoke a move to your S3 bucket. As you can see in the code above, the functions require some information that you will need to provide yourself such as your secret key – this can be found by logging in here.

And that’s that! As I said above the class can be used for more advanced manipulation of your S3 buckets and account, so do go and explore some of the things you can do with that, and have fun uploading!


Posted

in

by

Tags: