Upload Image to AWS S3 Using React

| By Webner

React provides you a facility to upload files directly from your react end to AWS S3. To achieve it, you need to install a package that is listed below:

npm install --save react-s3

After that, add the following import line to your js file at the top:

import S3FileUpload from 'react-s3';

Add a function to the onChange event of your input file element.

<input type="file" onChange={this.onFileChange} />

And add the below function in your component before the render function.

onFileChange = (file) =>{
//s3 bucket details
const config = {
bucketName: <S3_BUCKET>,
dirName: <folder_name>, //it’s optional
region: <S3_REGION>,
accessKeyId: <S3_KEY_ID>,
secretAccessKey: <S3_SECRET_KEY>
//upload file to s3
S3FileUpload.uploadFile(file, config)
console.log(data.location);// it return the file url
.catch((err) =>{

When you run this, you will see a “CORS” error in your network tab. To resolve it, open your bucket’s permission tab from the AWS Console account. After that, go to the “Cross-origin resource sharing (CORS)“ heading and paste the below code in the editor and save changes.

"AllowedHeaders": [
"AllowedMethods": [
"AllowedOrigins": [
"www.youdomain.com" //add your domain url here.
"ExposeHeaders": [
] }

Note: Don’t forget to replace the “www.youdomain.com” with your domain name.

Leave a Reply

Your email address will not be published. Required fields are marked *