How to Download multiple files from javascript

浪子不回头ぞ 提交于 2020-02-25 05:30:07

问题


I am trying to use window.location.href in a loop to download multiple files

I have a table in which i can select file's, then i run a loop of selected and try navigate to the file path to download the files.

I keep only getting the last file to download.

I think it's due to the location herf only taking action after my javascript finishes and not as the code runs.

When i have a break point on the window.location.herf it still only downloads the last file and only when i let the code run through.

Is there a better way to initiate multiple downloads from a javascript loop.


$("#btnDownload").click(function () {
  var table = $('#DocuTable').DataTable();
  var rows_selected = table.rows('.selected').data();
  $.each(rows_selected, function (i, v) {
    window.location.href = v.FilePath;
  });
});

回答1:


In some browsers (at least Google Chrome) support the follow:

$("<a download/>").attr("href", "https://code.jquery.com/jquery-3.1.0.min.js").get(0).click();
$("<a download/>").attr("href", "https://code.jquery.com/jquery-3.1.0.min.js").get(0).click();
$("<a download/>").attr("href", "https://code.jquery.com/jquery-3.1.0.min.js").get(0).click();

JSFiddle: https://jsfiddle.net/padk08zc/




回答2:


I would make use of iframes and a script to force the download of the files as Joe Enos and cmizzi have suggested.

The answer here will help with JavaScript for opening multiple iframes for each file: Download multiple files with a single action

The answers for popular languages will help with forcing downloads if the URL is actually something that can be served correctly over the web:

  • PHP: How to force file download with PHP
  • .Net: Force download of a file on web server - ASP .NET C#
  • NodeJS: Download a file from NodeJS Server using Express
  • Ruby: Force browser to download file instead of opening it

Ensure you change the links to point to your download script and also make sure you add the appropriate security checks. You wouldn't want to allow anyone to abuse your script.



来源:https://stackoverflow.com/questions/39452003/how-to-download-multiple-files-from-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!