How to get multiple files via ajax and download them as a zip file via JavaScript? -


would possible create client-site application written in javascript (that runs in browser) gets multiple image files via ajax, compresses them zip (or tar or whatever) , returns user file download (without server-side logic)?

workflow this:

  1. open website mydomain.com in browser
  2. website collects images mydomain.com/images/image1.png , mydomain.com/images/image2.jpg via ajax.
  3. both files automatically compressed archive file (e.g. zip, gzip or tar or whatever)
  4. user gets usual download prompt browser archive file.

so far think can part 1-2 running via jquery:

var urls = [   'image1.png',   'image2.jpg' ]; var images = []; var counter = 0;  function createarchive(images){   // how implement this? }  function download(archive){   // how implement this? }  (var = 0; i<urls.length; i++) {   $.ajax('images/' + urls[i]).done(function(data) {     images.push(data);     counter++;      // offer download of archive when ajax calls done     if (counter == urls.length){       var archive = createarchive(images);       download(archive);     }   }); } 

but here don't know how create zip file images array. how that?

important: has run in majors browsers ie, firefox, chrome, safari

holy moly! got work using these libs:

html

<!doctype html>  <html>    <head>     <title>zipper</title>     <script src="jszip.min.js"></script>     <script src="filesaver.min.js"></script>     <script src="script.js"></script>   </head>    <body>    </body>  </html> 

my script.js

var urls = [   'yufegi.jpg',   'duck.jpg' ]; var images = []; var counter = 0;  // http://stackoverflow.com/questions/6150289/how-to-convert-image-into-base64-string-using-javascript function convertimgtobase64url(url, callback, outputformat){     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(outputformat);       callback(dataurl, url);       canvas = null;     };     img.src = url; }  function createarchive(images){   // use jszip   var zip = new jszip();   var img = zip.folder("images");   (var i=0; i<images.length; i++) {     img.file(images[i].url, images[i].data, {base64: true});     }   var content = zip.generate({type:"blob"});    // use filesaver.js   saveas(content, "images.zip"); }  (var = 0; i<urls.length; i++) {   convertimgtobase64url(urls[i], function (base64img, url) {     images.push({       url: url,       data: base64img     });     counter++;     if (counter == urls.length) {       createarchive(images);     }   }); } 

Comments