Adding images from url to a zip file using jsZip

Sreeraj T A picture Sreeraj T A · Jan 2, 2015 · Viewed 8.3k times · Source

I am trying to create a zip file using jsZip . The contents of the zip file are images from the web. I have created the following code. But when i run it all am getting is an empty zip file of 22kb.

<html>
<body>
  <script type="text/javascript" src="jszip.js"></script>
  <script type="text/javascript" src="FileSaver.js"></script>
  <script type="text/javascript" src="jszip-utils.min.js"></script>
  <script>
    var imgLinks = ["url1", "url2", "url3"];

    function create_zip() {
      var zip = new JSZip();
      for (var i = 0; i < imgLinks.length; i++) {
        JSZipUtils.getBinaryContent(imgLinks[i], function(err, data) {
          if (err) {
            alert("Problem happened when download img: " + imgLink[i]);
            console.erro("Problem happened when download img: " + imgLink[i]);
            deferred.resolve(zip); // ignore this error: just logging
            // deferred.reject(zip); // or we may fail the download
          } else {
            zip.file("picture" + i + ".jpg", data, {
              binary: true
            });
            deferred.resolve(zip);
          }
        });
      }
      var content = zip.generate({
        type: "blob"
      });
      saveAs(content, "downloadImages.zip");
    }
  </script>
  <br/>
  <br/>
  <center>
    Click the button to generate a ZIP file
    <br/>
    <input id="button" type="button" onclick="create_zip()" value="Create Zip" />
  </center>
</body>
</html>

(url1 , url2 and url3 replaced by image urls i want to download).

Why am i getting these empty zip files?

Answer

David Duponchel picture David Duponchel · Jan 3, 2015

JSZipUtils.getBinaryContent is asynchronous : the content will be added after the call to zip.generate(). You should wait for all images before generating the zip file.

Edit :

If the files you are loading are on a different server, this server need to send additional HTTP headers, like Access-Control-Allow-Origin: server-hosting-the-page.com. The Firefox or Chrome debug console will show an error in that case. The js library can't detect a CORS issue (see here) and will trigger a success with an empty content.