Search code examples
javascriptdownloadzipopencpu

put multiple files in a zip file and download it using javascript


I have multiple image addresses. The address looks like https://tmp.ocpu.io/x05fcaa7ec4/graphics/last/png?width=800&height=600.

Above address may expire after 24 hours. So please just use following two addresses. http://r.ddmcdn.com/s_f/o_1/cx_633/cy_0/cw_1725/ch_1725/w_720/APL/uploads/2014/11/too-cute-doggone-it-video-playlist.jpg and https://static.pexels.com/photos/7720/night-animal-dog-pet.jpg.

I want to build a website that puts these two images (addresses) into a zip file and users can download the zip file. I don't know if this is possible but my following code works partially and I can download the zip file but it is just I can't open it with any image viewer software. Please help, thanks!

HTML

<!doctype html>
<html>

  <head>
    <title>Zipper</title>
    <script src="jszip.min.js"></script>
    <script src="stat_FileSaver.min.js"></script>
    <script src="script.js"></script>
  </head>

  <body>

  </body>

</html>

and JavaScript (the script.js)

var urls = [
  'http://r.ddmcdn.com/s_f/o_1/cx_633/cy_0/cw_1725/ch_1725/w_720/APL/uploads/2014/11/too-cute-doggone-it-video-playlist.jpg',
  'https://static.pexels.com/photos/7720/night-animal-dog-pet.jpg'
];
var images = [];
var counter = 0;

// From http://stackoverflow.com/questions/6150289/how-to-convert-image-into-base64-string-using-javascript
function convertImgToBase64URL(url, callback){
    var img = new Image();
    img.crossOrigin = 'Anonymous';
    img.onload = function(){
      var canvas = document.createElement('CANVAS'),
      ctx = canvas.getContext('2d'), dataURL;
      canvas.height = this.height;
      canvas.width = this.width;
      ctx.drawImage(this, 0, 0);
      dataURL = canvas.toDataURL();

      callback(dataURL, url);
      canvas = null;
    };
    img.src = url;
}

function createArchive(images){
  // Use jszip
  var zip = new JSZip();
  var img = zip.folder("images");

  for (var i=0; i<images.length; i++) {
    img.file(i+".jpg", images[i].data, {base64: true}); 
  }
      zip.generateAsync({type:"blob"}).then(function(file){
        saveAs(file, "images.zip");

      })

}

for (var i = 0; i<urls.length; i++) {
  convertImgToBase64URL(urls[i], function (base64Img, url) {
    images.push({
      url: url,
      data: base64Img
    });
    counter++;

    if (counter == urls.length) {
      createArchive(images);
    }
  });
}

Solution

  • images[i].data contains a data url (like data:image/png;base64,iVBOR...), you need to remove the data:image/png;base64, part to get the base64 content:

    var commaIdx = images[i].data.indexOf(",");
    img.file(i+".jpg", images[i].data.slice(commaIdx + 1), {base64: true});
    

    On a side note, when the images are on a different server, I get a CORS error. You may want to check that you won't get issues with this.