Blogs from the Ranch

< Back to Our Blog

Upload Directly to Amazon S3 with Support for CORS

To the cloud!

Our clients increasingly need features that rely on file uploads. In the past, we would typically use your average multi-part form with a file input and post the data to our servers. Once the file was done uploading, we would then turn around and push it to a cloud storage service.

But if you’re using Amazon Simple Storage Service (S3) to store your uploaded files, you can now upload files directly to Amazon without even touching your servers, speeding up your app in the process.

A couple of weeks ago, Amazon finally announced that S3 will now support Cross-Origin Resource Sharing (CORS). If you previously tried to be smart and post directly to your-bucket.amazons3.com with AJAX, you probably noticed an annoying “Origin not allowed” JavaScript error. Support for CORS fixes the problem by allowing you to specify which domains are allowed to communicate directly with your S3 bucket.

Add it to your app:

First, you’ll need to specify the domains and actions that you want to allow, since only GET requests are turned on by default. Log in to the S3 Console and select the bucket you want to use. Then click on “Properties” and then on the “Add CORS Configuration” button.

Then specify the actions you want. In this simple example, we just need GET and POST requests.

In our app, we will need to send a signature to S3 along with any metadata or access control parameters. Here’s some Ruby code to help you out:

Now let’s use the jQuery File Upload Plugin and put it all together to upload the files with AJAX:

This should securely upload a file and return a hash containing the exact file location.

Then you can just throw the location returned from S3 into a hidden field and submit the form to your server. Say goodbye to tying up processes with file uploads; now you can scale up to as many uploads as Amazon can handle.

Image credit: ahisgett

Not Happy with Your Current App, or Digital Product?

Submit your event

Let's Discuss Your Project

Let's Discuss Your Project