Search code examples
javascriptjszip

jszip only zipping one of the two files from url


I am trying to zip two files from an URL using the jszip add on and I am having a little issue. I am trying to zip two files from a url(testing with imgur links currently), however only one of my files is being zipped. I am not sure if it is something I am doing wrong in my foreach function?

Any suggestions would be awesome thank you.

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

(function () 
{
  var zip = new JSZip();
  var count = 0;
  var zipFilename = "instasamplePack.zip";
  var urls = [
    'https://i.imgur.com/blmxryl.png',
    'https://i.imgur.com/Ww8tzqd.png'
  ];

  function bindEvent(el, eventName, eventHandler) {
    if (el.addEventListener){
      // standard way
      el.addEventListener(eventName, eventHandler, false);
    } else if (el.attachEvent){
      // old IE
      el.attachEvent('on'+eventName, eventHandler);
    }
  }

  // Blob
  var blobLink = document.getElementById('kick');
  if (JSZip.support.blob) {
    function downloadWithBlob() {

      urls.forEach(function(url){
        var filename = "element" + count + ".png";
        // loading a file and add it in a zip file
        JSZipUtils.getBinaryContent(url, function (err, data) {
          if(err) {
            throw err; // or handle the error
          }
          zip.file(filename, urlToPromise(urls[count]), {binary:true});
          count++;
          if (count == urls.length) {
            zip.generateAsync({type:'blob'}).then(function(content) {
              saveAs(content, zipFilename);
            });
          }
        });
      });
    }
    bindEvent(blobLink, 'click', downloadWithBlob);
  } else {
    blobLink.innerHTML += " (not supported on this browser)";
  }

})();

Solution

  • When you do

    urls.forEach(function(url){
      var filename = "element" + count + ".png";               // 1
      JSZipUtils.getBinaryContent(url, function (err, data) {
        count++;                                               // 2
      });
    });
    

    you execute 1 two times and when a download finish you call 2. count is still zero in both cases (at 1), you overwrite one image with the other (same name).

    You also download each image two times: urlToPromise already calls JSZipUtils.getBinaryContent.

    To fix that:

    • use the index parameter of the forEach callback instead of count
    • JSZip accepts promises (and internally wait for them), urlToPromise already convert everything: use it
    • don't try to wait for promises, JSZip already does that

    This gives a new downloadWithBlob function:

    function downloadWithBlob() {
      urls.forEach(function(url, index){
        var filename = "element" + index + ".png";
        zip.file(filename, urlToPromise(url), {binary:true});
      });
      zip.generateAsync({type:'blob'}).then(function(content) {
        saveAs(content, zipFilename);
      });
    }