Search code examples
reactjsreact-nativecamera-rollrn-fetch-blob

React Native - Is it possible to download multiple assets using rn-fetch-blob?


Is there a way to download an array of objects (of .mp4, .jpg, etc...) using rn-fetch-blob? Right now this code is grabbing a single .mp4 url, but what if I have an array of .mp4 mixed in with some .jpg? How would I do such a thing?

say I have data:

const data = [
  {media: url.jpg}, 
  {media: url.mp4}, 
  {media: url.mp4}, 
  {media: url.jpg}
]

How do I setup my fetch so it will loop through data, and I can do something after CameraRoll?

RNFetchBlob.config({
  fileCache: true,
  appendExt: 'mp4',
}).fetch(
    'GET',
    'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4',
  )
  .then(res => {
    CameraRoll.saveToCameraRoll(res.path())
      .then(async () => {
        // works
      })
      .catch(err => console.log('err:', err));
  });

Thanks in advance for the help!


Edit: I haven't tested this, but just looking at what I wrote, is this going to be an issue?

for ( let foo of data ) {

  // write out some code to see if the url has .mp4 or .jpg extension?

  RNFetchBlob.config({
    fileCache: true,
    appendExt: 'mp4', // variable of the correct extension
  }).fetch(
      'GET',
      foo.media, // from the data object?
    )
    .then(res => {
      CameraRoll.saveToCameraRoll(res.path())
        .then(async () => {
          // works
        })
        .catch(err => console.log('err:', err));
    });
}

Or is there a much simpler way of doing this?


Solution

  • You can do something like this codes:

    const data = [
      {media: url.jpg}, 
      {media: url.mp4}, 
      {media: url.mp4}, 
      {media: url.jpg}
    ]
    
    data.map((item) => {
    
        const extention = item.media.split(".").pop(); // <-- get item extention
    
        RNFetchBlob.config({
            fileCache: true,
            appendExt: extention,  // <-- extention
        }).fetch(
            'GET',
            item.media, // <-- item url
        )
        .then(res => {
          CameraRoll.saveToCameraRoll(res.path())
          .then(async () => {
            // works
          })
          .catch(err => console.log('err:', err));
        });
    
    })