How can I let a user download multiple files when a button is clicked? How can I let a user download multiple files when a button is clicked? javascript javascript

How can I let a user download multiple files when a button is clicked?


The best way to do this is to have your files zipped and link to that:

The other solution can be found here: How to make a link open multiple pages when clicked

Which states the following:

HTML:

<a href="#" class="yourlink">Download</a>

JS:

$('a.yourlink').click(function(e) {    e.preventDefault();    window.open('mysite.com/file1');    window.open('mysite.com/file2');    window.open('mysite.com/file3');});

Having said this, I would still go with zipping the file, as this implementation requires JavaScript and can also sometimes be blocked as popups.


This was the method which worked best for me and didn't open up new tabs, but just downloaded the files/images I required:

var filesForDownload = [];filesForDownload( { path: "/path/file1.txt", name: "file1.txt" } );filesForDownload( { path: "/path/file2.jpg", name: "file2.jpg" } );filesForDownload( { path: "/path/file3.png", name: "file3.png" } );filesForDownload( { path: "/path/file4.txt", name: "file4.txt" } );$jq('input.downloadAll').click( function( e ){    e.preventDefault();    var temporaryDownloadLink = document.createElement("a");    temporaryDownloadLink.style.display = 'none';    document.body.appendChild( temporaryDownloadLink );    for( var n = 0; n < filesForDownload.length; n++ )    {        var download = filesForDownload[n];        temporaryDownloadLink.setAttribute( 'href', download.path );        temporaryDownloadLink.setAttribute( 'download', download.name );        temporaryDownloadLink.click();    }    document.body.removeChild( temporaryDownloadLink );} );


I fond that executing click() event on a element inside a for loop for multiple files download works only for limited number of files (10 files in my case). The only reason that would explain this behavior that made sense to me, was speed/intervals of downloads executed by click() events.

I figure out that, if I slow down execution of click() event, then I will be able to downloads all files.

This is solution that worked for me.

var urls = [  'http://example.com/file1',  'http://example.com/file2',  'http://example.com/file3']var interval = setInterval(download, 300, urls);function download(urls) {  var url = urls.pop();  var a = document.createElement("a");  a.setAttribute('href', url);  a.setAttribute('download', '');  a.setAttribute('target', '_blank');  a.click();  if (urls.length == 0) {    clearInterval(interval);  }}

I execute download event click() every 300ms. When there is no more files to download urls.length == 0 then, I execute clearInterval on interval function to stop downloads.