benjreinhart / react-native-aws3

Pure JavaScript React Native library for uploading to AWS S3
MIT License
398 stars 151 forks source link

Mulitple upload #101

Open lokomass opened 3 years ago

lokomass commented 3 years ago

Hi, I want to upload multiple files. My problem is, my function print "succedd up" and not reach "console.log('ok')" Here is my code Thanks for reply

import {
  RNS3
} from 'react-native-aws3'

export const UPLOAD = (data, exit, progress, success, error) => {
  return async() => {
    let echec = 0
    let array = []
    const options = {
      ...
    }
    Promise.all(
      data.forEach(async(item) => {
        RNS3
          .put(item, options)
          .progress(({ loaded, total }) => {
            progress(Math.round((loaded * 100) / total))
          })
          .then(response => {
            if (response.status === options.successActionStatus) {
              console.log('succedd up')
              array.push({
                file: item.name,
                id: item.article
              })
            } else {
              console.log('error up')
              echec++
            }
          })
      })
    )
    if (data.length === array.length) {
      console.log('ok')
      success(array)
    } else if (data.length === echec)  {
      console.log('ko1')
      error({
        message: 'Tout en erreur'
      })
    } else {
      console.log('ko2')
      error({
        message: 'Quelques erreurs'
      })
    }
  }
}
jheisondev commented 2 years ago
Promise.all(
  docsImg.map(async item => {
    const res = await RNS3.put(item, options);
    console.log('\n\n====>\n', res, '\n<=====\n\n');

    if (res.body.postResponse.location !== '') {
      const url = `${res.body.postResponse.location}|`;
      const aux = `${url}${urls === '' ? '' : '|'}${urls}`;

      setUrls(aux);
    }
  }),
).then(() => {
  console.log('\n\n====>\n', urls, '\n<=====\n\n');
});

Hi, I did it that way and it flowed well

esadkrs commented 1 year ago

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>'
  },
]