Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to upload multiple files? Solution #107

Open
esadkrs opened this issue Sep 21, 2022 · 0 comments
Open

How to upload multiple files? Solution #107

esadkrs opened this issue Sep 21, 2022 · 0 comments

Comments

@esadkrs
Copy link

esadkrs commented Sep 21, 2022

Creating a new issue to enhance attention

If you are wondering how to upload multiple files to S3 bucket...

Below worked for me!!!

Original Source

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>'
  },
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant