简体   繁体   中英

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;

        })
    }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM