Browser POST to S3, serverless style

Uploading to S3 is very useful, but requires authorization and/or permissions set on the bucket access, and achieving this from a plain old browser is a pain as it requires the POST to be approved and signed prior to sending it to the bucket.

All the implementations I have found require a server side component to sign the upload request, but I want to do it SERVERLESS!

So, I ended up adapting Leonid Shevtsov’s solution to work with Lambda – here comes serverless s3 upoads, and I hope it might help you too 🙂

Make sure you have an S3 Bucket, and a user that will provide the credentials for signing the upload request.

The user needs to have an AWS ACCESS_KEY and SECRET_KEY that will be used in the Lambda function, and an S3 PutObject permission for the bucket you created:

I did not encounter problems with CORS on the S3 bucket, so I did not set special CORS support on the bucket, but I did enable CORS for the Lambda function, in particular the API Gateway endpoint for my signing lambda.

So the HTML code performs 2 operations, sign and post

when a file is selected, jQuery triggers code that sends ajax GET to the lambda, the lambda then generates a new policy that allows the file upload, and signes the policy.

Then a form is populated with the response policy etc, and the submit button is enabled – so the form can POST to the S3 bucket directly from the browser!

Final thoughts: Authentication and permission for users to upload files to your bucket is not dicussed here – you can add it before creating the policy if you like… My approach is providing a way for anyone to upload an image (with a size limit) to the bucket – further processing of the image is done by a bucket trigger and images that are not going to be used in the system are immediately deleted.