Daniel Foreman
Daniel Foreman

Reputation: 125

Download images and download as Zip with JSZip and JS-Zip Utils

I'm attempting to download a couple of image files, and store it into a single zip file using JavaScript and JSZip. But this is returning an empty zip file. What am I doing wrong? I'm using JSZip and JSZip-Utils

function createZip() {

//Create zip file object
var zip = new JSZip();

//Add folders

//Add files
JSZipUtils.getBinaryContent("icons/8_Bit_Character.png", function (err, data) {
   if(err) {
      throw err; // or handle the error
   }
   zip.file("picture.png", data, {binary:true});
});

JSZipUtils.getBinaryContent("icons/16_Bit_Character.png", function (err, data) {
   if(err) {
      throw err; // or handle the error
   }
   zip.file("picture2.png", data, {binary:true});
});

//Compile all the data into memory.
var base64 = null;
if (JSZip.support.uint8array) {
  promise = zip.generateAsync({type : "uint8array"});
} else {
  promise = zip.generateAsync({type : "string"});
}

//Generate the zip file and download it.
zip.generateAsync({type:"base64"}).then(function (base64) {
    location.href="data:application/zip;base64," + base64; 
});

}

Upvotes: 3

Views: 7950

Answers (2)

SergejV
SergejV

Reputation: 468

Try using function from the Mini app : downloader example in documentation. This will fetch the content and return promise for that content / image.

function urlToPromise(url) {
return new Promise(function(resolve, reject) {
    JSZipUtils.getBinaryContent(url, function (err, data) {
        if(err) {
            reject(err);
        } else {
            resolve(data);
        }
    });
  });
}

zip.file(filename, urlToPromise(url), {binary:true});

Upvotes: 5

Alex Sysoiev
Alex Sysoiev

Reputation: 118

JSZipUtils.getBinaryContent inner function is happening asynchronously. So when you call zip.generateAsync, zip.file("picture.png", data, {binary:true}); hasn't happened yet.

Here is my example:

var count = 0;
.......
JSZipUtils.getBinaryContent(imageUrl, function (err, data) {
            if (err) {
                // throw err; // or handle the error
                console.log(err);
            }
            else {
                zip.file(fileName, data, { binary: true });
                count++;                    
                if (count == selectedImages.length) {                        
                    zip.generateAsync({ type: "blob" }).then(function (base64) {                            
                    //    window.location.replace("data:application/zip;base64," + base64);

                        saveAs(base64, `archive.zip`);

                        console.log("inner");
                    });
                }
            }
        });

Upvotes: 3

Related Questions