Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force/allow the user to download multiple files? (client side)

The input is a variable number of URLs (remote), all linking image resource. It is desired to allow user to allow to download all of these URLs in one batch. Since we are talking about 1000-2000 image resources, asking user to click "Save As..." for every URL is not feasible.

My original attempt was to download all the images into a blob (How to read loaded image into a blob?, did not work because of the same-origin policy), archive the file and allow the user to download it (all of this client side).

I was wondering what are possible alternative solutions? Whatever the solution is, it must not involve downloading the remote resources to the server at any time.

like image 217
Gajus Avatar asked Nov 12 '22 14:11

Gajus


1 Answers

Although it shouldn’t be possible, I managed to do this in Chrome with some sorcery. First you need to set the download attrbute to all your links f.ex:

<a href="http://example.com/image1.jpg" download>download</a>
<a href="http://example.com/image2.jpg" download>download</a>

Then create a synthetic click function:

function makeClick(element) {
    var evt = element.ownerDocument.createEvent('MouseEvents');
    evt.initMouseEvent('click', true, true,
        element.ownerDocument.defaultView, 1, 0, 0, 0, 0, false,
        false, false, false, 1, null);
    element.dispatchEvent(evt);
}​

Then just loop through your links and call it:

var links = document.getElementsByTagName('a');
for(var i=0;i<links.length; i++) {
    makeClick(links[i]);
}

Here is a demo: http://jsfiddle.net/37pFC/

In Chrome you will get a warning saying something like "This site wants you to download multiple files. Allow?" but this might be manageable.

Disclaimer: I havent tried in other browsers, and I don’t think it’s very cross-browser friendly.

like image 76
David Hellsing Avatar answered Nov 15 '22 06:11

David Hellsing