1

I am trying to download multiple files from multiple URL's using javascript so far I have tried multiple options but it works only for 1 URL.

I have an array of URL's that needs to start multiple downloaded in the browser.

$(fileUrls).each(function(_index, fileUrl: any) {
  let tempElement: any;
  tempElement = document.createElement("A");
  tempElement.href = fileUrl;
  tempElement.download = fileUrl.substr(fileUrl.lastIndexOf("/") + 1);
  document.body.appendChild(tempElement);
  tempElement.click();
  document.body.removeChild(tempElement);
});

Also tried using

$(fileUrls).each(function (_index, fileUrl: any) {
  window.location.href = fileUrl;
});

But it works for only 1 URL rest of the calls fails with below warning message in the browser

Resource interpreted as Document but transferred with MIME type application/octet-stream

Rastalamm
  • 1,712
  • 3
  • 23
  • 32
Nilesh
  • 135
  • 1
  • 2
  • 12

1 Answers1

0

You can achieve this using below code.

create one array and pass all the file locations which you want to download like below.

var files= [
      'file1_Link',
      'file2_Link',
      'file3_Link'
    ];

function to download all the files. we are creating the anchor tag with download attribute and on loop we need to click on that link. please see below ex.

    function downloadAll(files){
    if(files.length == 0) return;
    file = files.pop();
    var theAnchor = $('<a />')
        .attr('href', file[0]) // set index accordingly
        .attr('download',file[0]) // set index accordingly
        // Firefox does not fires click if the link is outside
        // the DOM
        .appendTo('body');

    theAnchor[0].click(); 
    theAnchor.remove();
    downloadAll(files);
}

// call the function like below to achieve your goal

downloadAll(files);
Dheeraj Kumar
  • 146
  • 1
  • 10
  • could you please create stackblitz of your issue. it will be helpful for fix your issue quickly. – Dheeraj Kumar Jul 24 '19 at 11:43
  • or you can follow : https://stackoverflow.com/questions/18451856/how-can-i-let-a-user-download-multiple-files-when-a-button-is-clicked . it might be solved your issue – Dheeraj Kumar Jul 24 '19 at 11:46