Connecting to AWS S3, Uploading and Retrieving Files from AWS S3
Steps to upload images in AWS S3 buckets:
First, you need to install the following libraries to your project using either npm or yarn. Here are links to each of them on npm
npm i aws-sdk
npm i react-native-image-picker
npm i base64-arraybuffer
npm i react-native-fs
Then, you need to create an AWS IAM account and an S3 bucket using your AWS account. If you don’t know how to create an IAM user please refer to this article. The only changes you need to make are to assign programmatic access to your user and set AmazonS3FullAccess permission. Please make sure to save the access key ID and secret access key for later.
Also, you can simply select s3 service from your AWS console and create an s3 bucket. Remove the tick from “Block all public access” to make the bucket public.
After creating the bucket, add the following policy as a bucket policy:
Then we need to implement a method to choose images from the gallery or take with the camera using the React native image picker:
In the above example, I have only enabled Upload from the gallery and Take from Camera options. You
Now we can implement the method for image uploading:
Here I converted the image file to base 64 using file stream and then into an array buffer because aws-sdk supports a few data types, like strings and array buffers, to be uploaded using that.