Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through array of file urls and download each one with React

I'm trying to do what I 'thought' would be a simple task. I have an array of URLs that I'd like to loop through and download on to the client machine when the user clicks a button.

Right now I have a parent component that contains the button and an array of the urls (in the state) that I'd like to loop through and download. For some reason, the way I'm doing it now only downloads one of the files, not all of the contents of the array.

Any idea how to do this correctly within React?

handleDownload(event){
        var downloadUrls = this.state.downloadUrls;
        downloadUrls.forEach(function (value) {
            console.log('yo '+value)
        const response = {
              file: value,
        };                
            window.location.href = response.file;

        })
    }
like image 270
JDun Avatar asked Oct 30 '22 08:10

JDun


1 Answers

I would use setTimeout to wait a little bit between downloading each files.

handleDownload(event){
    var downloadUrls = this.state.downloadUrls.slice();
    downloadUrls.forEach(function (value, idx) {
        const response = {
          file: value,
        };
        setTimeout(() => {
            window.location.href = response.file;
        }, idx * 100)
    })
}

In Chrome, this will also prompt the permission asking for multiple files download.

like image 61
Tom Chen Avatar answered Nov 17 '22 12:11

Tom Chen