javascript 如何使用 window.location.href 下载多个文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18453595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:59:17  来源:igfitidea点击:

How can I use window.location.href to download multiple files?

javascriptdownload

提问by Grammin

I have the following javascript:

我有以下 javascript:

function downloadFiles(){
  var files = [];
  files.push('mysite.com/file1.txt');
  files.push('mysite.com/file2.txt');
  files.push('mysite.com/file3.txt');

  for(var ii=0; ii<files.length; ii++){
    window.location.href = files[ii];
  }
}

The problem is this only downloads the last file in the list because the first two files get overwritten by the last one. How can I wait for the user's input on each file before moving on to the next file?

问题是这只会下载列表中的最后一个文件,因为前两个文件被最后一个覆盖。在继续下一个文件之前,如何等待用户对每个文件的输入?

回答by Grammin

What I ended up doing:

我最终做了什么:

function downloadFiles(){
  var files = [];
  files.push('file1.txt');
  files.push('file2.txt');
  files.push('file3.txt');

  for(var ii=0; ii<files.length; ii++){
    downloadURL(files[ii]);
  }
}

var count=0;
var downloadURL = function downloadURL(url){
  var hiddenIFrameID = 'hiddenDownloader' + count++;
  var iframe = document.createElement('iframe');
  iframe.id = hiddenIFrameID;
  iframe.style.display = 'none';
  document.body.appendChild(iframe);
  iframe.src = url;
}

回答by Chris Young

If you change your code to use window.open()instead of window.location, you can launch all three downloads at the same time.

如果您将代码更改为使用window.open()而不是window.location,则可以同时启动所有三个下载。

I know this doesn't satisfy the requirement of waiting on the user's input before presenting each of the downloads, but it does build off of the spirit of your original code. Hopefully it will help a little.

我知道这不能满足在呈现每个下载之前等待用户输入的要求,但它确实建立在您原始代码的精神之上。希望它会有所帮助。

function downloadFiles(){
  var files = [];
  files.push('file1.txt');
  files.push('file2.txt');
  files.push('file3.txt');

  for(var ii=0; ii<files.length; ii++){
    window.open(files[ii]);
  }
}