最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I use window.location.href to download multiple files? - Stack Overflow

programmeradmin2浏览0评论

I have the following javascript:

function downloadFiles(){
  var files = [];
  files.push('mysite/file1.txt');
  files.push('mysite/file2.txt');
  files.push('mysite/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?

I have the following 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?

Share Improve this question edited Aug 27, 2013 at 5:39 Chris Farmer 25.4k36 gold badges123 silver badges168 bronze badges asked Aug 26, 2013 at 21:47 GramminGrammin 12.2k24 gold badges83 silver badges140 bronze badges 1
  • You could add an iframe to the DOM for each file in your list and set the iframe's src to the appropriate file url. – Chris Farmer Commented Aug 27, 2013 at 5:38
Add a comment  | 

3 Answers 3

Reset to default 10

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

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

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

old one but the solution for this that I ended up going with is the following

let currentIndex = 0;
const intervalId = setInterval(() => {
  if (currentIndex === files.length - 1) clearInterval(intervalId);
  window.location.href = files[currentIndex];
  currentIndex++;
}, 1000);
发布评论

评论列表(0)

  1. 暂无评论