Browser uploads to DreamObjects using PHP

dreamobjects

#1

I’ve been working on some sample code for an upcoming blog post and thought someone would find it useful. It uses PHP, HTML and JavaScript - no special libraries required.

This allows anyone to upload a file to your DreamObjects account. The file is uploaded from the browser so the file never goes through your web server. In this sample, the file is uploaded in a directory called uploads in the bucket you specify in the configuration.

You’ll want to be careful since this allows anyone to upload anything to your account. Probably best to put this behind a password protected area.

Also, you can modify the policy document to be restrictive, including limiting max upload size and specific file types. More info here - http://docs.aws.amazon.com/AmazonS3/latest/dev/HTTPPOSTForms.html#PolicyConditions

[php]

<?php // Inspiration from http://birkoff.net/blog/post-files-directly-to-s3-with-php/ // User configured fields $access_key = 'Your_Access_Key'; $secret_key = 'Your_Secret_Key'; $bucket = 'Your-Bucket'; $acl = 'public-read'; // if you prefer you can use 'private' $success_action_redirect = 'http://www.dreamhost.com'; // Create the timestamp we will call it $expire $now = strtotime(date("Y-m-d\TG:i:s")); $expire = gmdate('Y-m-d\TG:i:s\Z', strtotime('+ 10 minutes', $now)); // credentials valid 10 minutes from now $url = 'https://'.$bucket.'.objects.dreamhost.com'; $policy_document=' {"expiration": "'.$expire.'", "conditions": [ {"bucket": "'.$bucket.'"}, ["starts-with", "$key", "uploads/"], {"acl": "'.$acl.'"}, {"success_action_redirect": "'.$success_action_redirect.'"}, ["starts-with", "$Content-Type", ""] ] }'; // create policy $policy = base64_encode($policy_document); // create signature $signature = base64_encode(hash_hmac("sha1", $policy, $secret_key, $raw_output = true)); ?> DreamObjects POST Form
  File to upload to DreamObjects: 
  <input name="file" type="file" id="file">
  <br> 
  <input type="submit" value="Upload File to DreamObjects"> 
</form> 
<script>
  // Guess the mimetype and update the Content-Type
  // Inspired from http://jsbin.com/akati3/2
  file = document.getElementById('file');
  file.addEventListener('change', function() {
    document.forms["uploadForm"]["Content-Type"].value = file.files[0].type;
  }, false);
</script>
[/php]

#2

Thanks Justin. This could be useful for creating simple applications. Could this be made to return a url to the uploaded file? That would be nice for giving the uploader a link or storing it for later.


#3

I’ve been trying to get my example to work and haven’t made it return the URL yet. The issue I’m running into is that the policy document is compiled at page load so it’s not updated to automatically redirect to the file. There’s probably some JS that could update the success_action_redirect.

An easy option would be to override the filename (e.g. timestamp, random) and use that instead.