Upload Image to AWS S3 Using React
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.
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)
.then((data)=>{
console.log(data.location);// it return the file url
})
.catch((err) =>{
alert(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.
Note: Don’t forget to replace the “www.youdomain.com" with your domain name.
Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.
Originally published at https://blog.webnersolutions.com on July 30, 2021.