Upload images on a React app to AWS S3 Bucket
We ll got throw a way to upload pictures to a React app and save its Url to a Rails backend. by using AWS S3 Amazon Simple Storage Service.
First, you need an AWS account, if you don’t have it follow this link to create one.
Create & Config an S3 Bucket
login to your AWS account and open dashboard.
Click S3 object storage. you can use an existing Bucket or Create a new one.
The Bucket is where you 'll be storing your files (images …)
When you create a new Bucket you 'll be asked to Enter a name and select the region witch you ll need later in the uploading configuration at your React app.
Then Click on the Bucket That you want to use and go to permissions tab. and then Click on CORS configuration.
Edit the CORS configuration.
Enter this XML code below in the editor.
In <AllowedOrigin>*</AllowedOrigin> you can give permissions to a specific website or enter * to allow requests from any App
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>PUT</AllowedMethod>
<AllowedMethod>POST</AllowedMethod>
<AllowedMethod>DELETE</AllowedMethod>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
</CORSRule>
</CORSConfiguration>
Cross Origin Resource Sharing CORS allows you to access files from outside the domain the file is hosted on.
After that, you want to get the Access keys (access key ID and secret access key). Click on your name on the top right corner of the dashboard
Then click on My Security Credentials.
Click on Create new Access Key and you 'll be prompted to download Access keys. Make sure you securely save them, you will need both access key ID and secret access key in your application.
Back to React Application
Now you have all that you need to config your uploading(Bucket name, region, access key ID and secret access key)
First, you need to install the S3FileUpload library that helps to upload any type of files to Amazon AWS S3.
Uploading.js Component
In Uploading.js Component import S3FileUpload
and Configure AWS with your access key id, secret access key, Bucket Name, And the region.
You May Create a folder in the Bucket and add its name to dirName or you can just leave blank .
const config = { bucketName: 'Enter Your bucket Name ', dirName: 'Enter Folder Name ', /* optional */ region: 'Enter Your Bucket region', accessKeyId: 'Enter accessKeyId here', secretAccessKey: 'Enter secretAccessKey'}
Add an input element with type file and a Method to handle the change.
Add the Below code to the upload method
The response of S3FileUpload.uploadFile will be an image object witch include a URL in the data.location
Now you can console.log data.location and get the URL of the file that you upload and you can use it in your application or save it in the backend Database.
Thank You for reading. Feel free to comment and happy coding