简体   繁体   English

循环遍历文件URL数组并使用React下载每个文件URL

[英]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. 当用户单击按钮时,我有一系列URL,我想循环并下载到客户端计算机上。

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. 现在我有一个父组件,其中包含按钮和一个url(状态)数组,我想循环并下载。 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? 知道怎么在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. 我会使用setTimeout在下载每个文件之间稍等一下。

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. 在Chrome中,这也会提示要求下载多个文件的权限。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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