2017-07-17 127 views
0

我正在使用javascript从url下载多个文件。使用javascript不能正常工作的多文件下载

我已经使用了以下网址这样做,但没有找到任何解决方案,

其工作罚款,火狐和谷歌Chrome,但不与IE和边缘

我用下面的代码工作。

reportFileList.forEach((report, index) => { 
    var downloadUrl = report 
    setTimeout(function() { 
     var a = document.createElement('a'); 
     a.href = downloadUrl; 
     a.target = '_parent'; 
     if ('download' in a) { 
      a.download = downloadUrl; 
     } 

     (document.body || document.documentElement).appendChild(a); 
     if (a.click) { 
      a.click(); // The click method is supported by most browsers. 
     } 
     a.parentNode.removeChild(a); 
    }, 500); 
}); 
+2

你的浏览器中有任何错误**开发人员**工具控制台? –

+0

不,我没有得到任何错误,它只是下载最后的文件 –

+0

其工作正常的Firefox和谷歌浏览器,但没有与IE和边缘 –

回答

0

我已经通过下面的代码解决了这个问题 - > 可能是其帮助别人。

function download_files(files) { 
function download_next(i) { 
if (i >= files.length) { 
    return; 
} 
var a = document.createElement('a'); 
a.href = files[i].download; 
a.target = '_blank'; 

if ('download' in a) { 
    a.download = files[i].download; 
} 

(document.body || document.documentElement).appendChild(a); 
if (a.click) { 
    a.click(); // The click method is supported by most browsers. 
} 
else { 
    window.open(files[i].download); 
} 
console.log('1'); 
a.parentNode.removeChild(a); 
setTimeout(function() { 
    download_next(i + 1); 
}, 5000); 
} 
// Initiate the first download. 
download_next(0); 
} 

function do_dl() { 
download_files([ 
    { download: "https://www.example.com"}, 
    { download: "https://www.example.com"}, 
    { download: "https://www.example.com"}, 
    { download: "https://www.example.com"}, 
]); 
}; 


do_dl(); 
0

这段代码工作(在Chrome测试)的问题必须在别处:

  • 也许reportFileList VAR的格式不正确。
  • 某些浏览器提示您进行多次下载,必须启用它。

例子:http://js.do/code/161479

<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> 
<p style="line-height: 18px; font-size: 18px; font-family: times;"> 
Click "<i>Load samples</i>" to view and edit more JS samples.<br> 

<script> 
var reportFileList = ['https://www.example.com','https://www.example.com','https://www.example.com']; 
reportFileList.forEach((report, index) => { 
      var downloadUrl = report 
       setTimeout(function() { 
        var a = document.createElement('a'); 
        a.href = downloadUrl; 
        a.target = '_parent'; 
        if ('download' in a) { 
         a.download = downloadUrl; 
        } 

        (document.body || document.documentElement).appendChild(a); 
        if (a.click) { 
         a.click(); // The click method is supported by most browsers. 
        } 
        a.parentNode.removeChild(a); 
       }, 500); 



    }); 
</script> 
+0

是的,它对铬的工作很好,你有清楚的检查我的问题吗? –

+0

我已经清楚地阅读了您的问题,问题在于您编辑了问题以后包含这些详细信息:https://stackoverflow.com/posts/45143177/revisions –