How to upload binary files to S3 using React, AWS Lambda, and NodeJS
Uploading files in environments where the backend and the frontend is separated can be a little tricky compared to monolithic applications. In this article I will show you a way to upload files to S3 using React and Lambda functions with Node.
First things first
Create a bucket where you are going to store your files. For the sake of simplicity I will use the following bucket policy:
Be aware that this policy will make your bucket public, and it might not be what you want.
Send the files from the frontend
In your component create a form:
The submitFile
and the handleFileUpload
functions will look like this:
In this example I only upload one file to my server. We store the selected files in the state of the component. On submit we create the FormData Object, append our file, and then post it to our endpoint. Note the Content-Type header.
Handle the request
Here we are going to use a node module to parse the incoming form data: busboy.
Let’s create a parser function which takes the event
object as an argument, and parses the files from the request into the event.body
.
Depending on your run environment the Content-Type header might change to content-type. As a workaround I implemented the
getContentType
function.
Long story short: this function returns a promise which gets resolved when busboy finishes the parsing of the FormData, and it returns the new event
object.
Now let’s create a function which handles the actual upload of the file to S3.
And now the final step: wire the pieces together. Your main
function should look something like this:
Hope this tutorial helped you achieve your goal. If you have any thoughts about this article, or improvements, I’d be happy to hear it. Constructive criticism appreciated 🍻
Daniel