Contact Archives
 

How to use Amazon S3 with Dropzone.js

 

Recently I had to implement the classic “Create New Post” with attachments for a site I’m creating (more about that on another post); to do so I’ve chosen ExpressJS + Dropzone.js + Amazon S3, but you can implement it using your preferred dev stack.

The problem

I wanted to upload to Amazon S3 using Dropzone (while allowing multiple paralell uploads) but this time without touching the server (almost).

Research

This is possible because it was added back in 2009 so I only needed to check there to see how to implement it.

TL;DR: Amazon S3 requires you to send a signed policy with each upload to verify that the upload is legitimate.

Another helpful link was the Dropzone.js Issue #33 @ GitHub which pointed me in the right direction for writing this article. Be sure to check that out too.

TL;DR: My idea wasn’t crazy, people already tried and succeeded doing this. Always a good sign.

Solution

The proposed solution comprises the following steps

  1. Configure CORS on your bucket so you allow POST/PUT.
    • I’ve made this development only gist so you can get started faster, but remember to change it so it only allows requests coming from your domain.
  2. Modify Dropzone.js so it sends data about the uploads to the server before starting the upload to Amazon S3, so we can have the required info to execute the next step.
  3. Create a valid S3 Policy file based on the upload info, the Amazon S3 Policy Generator should help you accomplish this task.
  4. Sign the policy file using your secret key and output a JSON string for the server
    • Note: On this step I also generate a random filename to avoid people from guessing.
  5. Modify Dropzone so it sends this JSON along with the upload.
  6. Once Dropzone finishes the upload it will need to append an input type hidden to the form so we can read it whenever the user submits the form.
  7. Upload your first file and enjoy not having to deal with uploads on server side :)

The final gist with the Frontend JS + ExpressJS controller method is available at https://gist.github.com/francolaiuppa/76f4b60cd46a15d325cf

Hope this helps you, if you have any comments/doubts/questions feel free to leave those in the comments section.

Thanks for reading!