循环遍历文件URL数组并使用React下载每个文件URL [英] Loop through array of file urls and download each one with React

查看:273
本文介绍了循环遍历文件URL数组并使用React下载每个文件URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力做我认为'这将是一项简单的任务。我有一系列网址,当用户点击按钮时,我想循环并下载到客户端计算机。

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. For some reason, the way I'm doing it now only downloads one of the files, not all of the contents of the array.

任何想法如何正确地做到这一点在React中?

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;

        })
    }


推荐答案

我会使用setTimeout在下载每个文件之间稍等一下。

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)
    })
}

在Chrome中,这也会提示要求下载多个文件的权限。

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

这篇关于循环遍历文件URL数组并使用React下载每个文件URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆