How can I upload files to Amazon S3 using react-dropzone?

Viewed 2230

I've been working on a project involving the react-dropzone package. I successfully built a container me to add files but now I can't figure out how I can upload these files to my Amazon S3 bucket. When I add files, it creates these "file" objects but all it contains is information like the name, size, path, etc. Doesn't seem like it contains the actual file itself. Even the file path isn't the full file path, its just the name of the file. The documentation doesn't have any information on what you can do after dragging a file to the browser. I don't believe this entire package that has 1.3 million NPM downloads per week is all for display purposes. I'm still new to the world of web-dev so there's probably something obvious I don't understand. Any advice?

2 Answers

react-dropzone is a simple component used to get File objects from the user. These Files implement the File API found here: https://developer.mozilla.org/en-US/docs/Web/API/File

The File object itself is the file. It also has properties such as size, path, etc.

react-dropzone does not handle any sort of uploading, or do anything with those files, thats your responsibility.

As far as I know, you cannot directly upload a file to S3 from the web. You will need a server/lambda endpoint to generate a signed url, that you can then use in your client to PUT the file to.

So it becomes a 3 step process.

  1. Get the File from react-dropzone
  2. Request a signedUrl from your endpoint
  3. PUT the file to the signedUrl

Here is an example: https://medium.com/@kevinwu/client-side-file-upload-to-s3-using-axios-c9363ec7b530

What you're looking for is the FormData object Here's an example using axios

for (let i = 0; i < newFiles.length; i++) {
    let file = newFiles[i]
    let formData = new FormData()
    formData.append("file", file)
    formData.append("otherProperties", otherProperties)
    await axios.post(url, formData, {
        headers: {
            'content-type': 'multipart/form-data',
            Authorization: `Bearer ${token}`,
        }
    }).then(res => {
        console.log(res.data)
        successfulUploads.push(res.data)
    }).catch(err => {
        console.log(err)
    })
}
Related