Upload files to S3 buckets from react

mohitkyadav

Mohit Kumar Yadav

Posted on September 6, 2020

Upload files to S3 buckets from react

Disclaimer - When uploading files to s3 directly from front end, your AWS credentials are exposed in the network tab. Refrain from uploading files to protected S3 buckets directly from FE. Always use a server to upload files.

You need to install aws-sdk npm package in order to upload files to s3 buckets.

npm install aws-sdk --save

Make sure the bucket has following policy

<?xml version="1.0" encoding="UTF-8"?>
 <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <CORSRule>
        <AllowedOrigin>*</AllowedOrigin>
        <AllowedMethod>POST</AllowedMethod>
        <AllowedMethod>GET</AllowedMethod>
        <AllowedMethod>PUT</AllowedMethod>
        <AllowedMethod>DELETE</AllowedMethod>
        <AllowedMethod>HEAD</AllowedMethod>
        <ExposeHeader>ETag</ExposeHeader>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
</CORSConfiguration>
Enter fullscreen mode Exit fullscreen mode

The ETag header must be exposed or bigger uploads will not complete.


Let's write some React
import AWS from 'aws-sdk'

in the component constructor set the AWS access key and the secret keys. You get them straight from the aws console.

AWS.config.update({
  accessKeyId: AWSAccessKeyId,
  secretAccessKey: AWSSecretKey
})
Enter fullscreen mode Exit fullscreen mode

Create the bucket in the constructor as well
Always double check bucket's name and region.

this.myBucket = new AWS.S3({
  params: { Bucket: 'video-bucket-xyz'},
  region: 'ap-south-1',
})
Enter fullscreen mode Exit fullscreen mode

Now when ever you want to upload a file to the bucket call the following function and pass the selected file as function argument.

uploadFile = (file) => {
  const params = {
    ACL: 'public-read',
    Key: file.name,
    ContentType: file.type,
    Body: file,
  }
  this.myBucket.putObject(params)
    .on('httpUploadProgress', (evt) => {
      // that's how you can keep track of your upload progress
      this.setState({
        progress: Math.round((evt.loaded / evt.total) * 100),
      })
    })
    .send((err) => {
       if (err) {
         // handle the error here
       }
    })
}
Enter fullscreen mode Exit fullscreen mode

you can read more about putObject here.


References
aws-sdk

💖 💪 🙅 🚩
mohitkyadav
Mohit Kumar Yadav

Posted on September 6, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related