1

In my react component I have a function which use file-saver package to save an array of files.

File-saver package installation:

npm i file-saver

My react component:

import { saveAs } from 'file-saver'

saveImg(urlArr){
    urlArr[0];
    let name = 'img' + 0 + '.jpg';
    saveAs(urlArr[0], name)
    urlArr[2];
    let name2 = 'img' + 2 + '.jpg';
    saveAs(urlArr[2], name2)
}

, and it works but my expectation was downloading files instead of opening images in new browser tabs. I would like to trigger downloading from react component. How to force downloading? What are others libraries used for downloading?

ElConrado
  • 1,477
  • 4
  • 20
  • 46

2 Answers2

2

Yes I tried on codesandbox and in case of URL, file-saver will open a new tab instead of download image. But, you could try to use the blob way:

import { saveAs } from 'file-saver'

saveImg(urlArr){
    (async () => {
       let name = 'img' + 0 + '.jpg';
       let blob = await fetch(urlArr[0]).then((r) => r.blob());
       saveAs(blob, name);
    })();
    (async () => {
       let name2 = 'img' + 2 + '.jpg';
       let blob2 = await fetch(urlArr[2]).then((r) => r.blob());
       saveAs(blob2, name2);
    })();  
}
Giovanni Esposito
  • 10,696
  • 1
  • 14
  • 30
1

Building upon @Giovanni Esposito answer above,

Thank you Giovanni for answer, however, The fetch requests i made to firebase storage were blocked by CORS and so the method failed to work at first.

In case anyone else experiences the issue, being blocked by CORS. You will have make additional configuration with your Firebase Storage.

This post talks about the configuration you need to make with Google cloud to get the requests working.

For my case, i was making requests from localhost with react.js. below is the snippet i had to add to my cors.json file.

[
    {
      "origin": ["http://localhost:3000"],
      "method": ["GET"],
      "maxAgeSeconds": 3600
    }
]

I hope this helps anyone else who came across my issue.

Tonny Bawembye
  • 496
  • 5
  • 16