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.
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
Interested in learning more about our basic and advanced Back-End Courses?
Learn from the experts at a Big Nerd Ranch Bootcamp!
Interested in leveling up your coding skills from the same authors of the Big Nerd Ranch Guide? Subscribe to The Frontier today!