Search

Upload Directly to Amazon S3 with Support for CORS

Patrick Van Stee

2 min read

Sep 10, 2012

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

Steve Sparks

Reviewer Big Nerd Ranch

Steve Sparks has been a Nerd since 2011 and an electronics geek since age five. His primary focus is on iOS, watchOS, and tvOS development. He plays guitar and makes strange and terrifying contraptions. He lives in Atlanta with his family.

Speak with a Nerd

Schedule a call today! Our team of Nerds are ready to help

Let's Talk

Related Posts

We are ready to discuss your needs.

Not applicable? Click here to schedule a call.

Stay in Touch WITH Big Nerd Ranch News