2017-07-17 128 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 –