Download multiple images into 1 zip file

Jason Brewer picture Jason Brewer · Aug 3, 2015 · Viewed 24k times · Source

I have a function that currently downloads multiple images and saves them to a users "download" folder (Only works in Chrome)

I want to take this function to the next step and put these images in a single zip file.

Below is an example of my current code. I want to merge my code with the JSZip API I found online here.

I have done the bower install for this JSZip API already and included the script in my html.

Here is my code that works perfectly downloading multiple SINGLE images at once:

$scope.downloadPhotos = function() {
    var photoUrls = [];
    for (var x = 0; x < $scope.$parent.photos.length; x++) {

        var p = $scope.$parent.photos[x];
        if (p.isChecked) {
            photoUrls.push($scope.bucketUrl() + p.photoUrl);

        }
    }

    saveImage(photoUrls);
};



/*----this function  saveImage works great (only Chrome)-----*/
    function saveImage(urls) {
        var link = document.createElement('a');

        link.setAttribute('download', null);
        link.style.display = 'none';


        document.body.appendChild(link);

        for (var i = 0; i < urls.length; i++) {
            link.setAttribute('href', urls[i]);
            link.click();
        }

        document.body.removeChild(link);
    }

And here is the JSZip API code example to create a zip file with content in it:

function create_zip() {
    var zip = new JSZip();
    zip.add("hello1.txt", "Hello First World\n");
    zip.add("hello2.txt", "Hello Second World\n");
    content = zip.generate();
    location.href = "data:application/zip;base64," + content;
}

Now I'm just wondering how to combine the two to put my images into a zipfile. Thanks for your help!

Answer

Jaitsujin picture Jaitsujin · Dec 20, 2018

I put this together that will let you zip an array of image urls.

https://jsfiddle.net/jaitsujin/zrdgsjht/

You can manage zip folder structure by modifying this line

filename = filename.replace(/[\/\*\|\:\<\>\?\"\\]/gi, '').replace("httpsi.imgur.com","");