In my previous article, I explained how to get multiple images using react-native-image-crop-picker
, and in this post, I'll cover how to upload those images to the AWS S3 server.
For that I used react-native-aws3
, this library has no native dependencies so I preferred it over others libraries.
Install react-native-aws3
Please go through their website to install and set IAM's policy as mentioned.
Upload button and onPress
Now I created a simple button like this
<Button
onPress={onUploadClick}
title="Upload"
/>
as react-native-aws3
upload a single image to S3 at a time but I have multiple images to upload so I used Promise.all
.
const uploadButtonClick = () => {
let promises = [];
images.map((image, i) => {
promises.push(uploadImageToS3(image));
});
}
Here I created an empty array of promises to store each response of the upload call. Next, I am mapping images array to upload calls with a single image and promises.push
is saving that response in promises array.
RNS3.put
Next, I defined my uploadImageToS3
a method like its mentioned in the example of react-native-aws3
.
const uploadImageToS3 = async image => {
const options = {
keyPrefix: "uploads/",
bucket: "your-bucket",
region: "us-east-1",
accessKey: "your-access-key",
secretKey: "your-secret-key",
successActionStatus: 201
}
const file = {
uri: `${image.path}`,
name: image.path.substring(image.path.lastIndexOf('/') + 1), //extracting filename from image path
type: image.mime,
};
return new Promise((resolve, reject) => {
RNS3.put(file, options)
.then(res => {
if (res.status === 201) {
const {postResponse} = res.body;
resolve({
src: postResponse.location,
});
} else {
console.log('error uploading to s3', res);
}
})
.catch(err => {
console.log('error uploading to s3', err);
reject(err);
});
});
};
This method is returning the promise of URL/location of the image as an object having value src
.
Now I combined all promises with Promise.all
function.
Promise.all(promises).then(uploadedImgs => {
console.log('Yayy, all images are uploaded successfully', uploadedImgs)
});
uploadedImgs
array will look like this
[
{
src: 'https://<image-url>'
},
{
src: 'https://<image-url>'
},
]
In the above code, I am only displaying console message but I needed this array of images to send to another API call. So you can use this array in your state or send it to the database according to your need.
That's all for today, Thanks for reading!