Adding JSzip to the project

Date posted: May 5, 2015

I have been working on a project were I need to download html and images from a website combined in one zip file. I found out about: JSzip. This Library does the job. The first problem: Multiple XMLHttpRequest for downloading the images. Al the time I only received the response result after from the last XMLHttpRequest.

I wrote a recurring function to solve this problem:

here is the complete script:


var aImagesSrcs = [],
iCounter = 0,
zip = new JSZip(),
imageFolder = zip.folder("images"),
newsletterName = 'newsletter.html';

function grabImages(){
if (iCounter < aImagesSrcs.length){ try{ var filename = aImagesSrcs[iCounter].replace(/^.*[\\\/]/, ''); console.log(filename); var xhr = new XMLHttpRequest(); xhr.open('GET', aImagesSrcs[iCounter], true); xhr.responseType = "arraybuffer"; xhr.onreadystatechange = function(evt) { if (xhr.readyState === 4) { if (xhr.status === 200) { imageFolder.file(filename, xhr.response); iCounter++; grabImages(); } } }; xhr.send(); } catch(e){ alert('Issue with browser.') } } if(iCounter == aImagesSrcs.length){ var content = zip.generate({type:"blob"}); saveAs(content, "newsletter.zip"); console.log("AND IT IS SAVED, YOU DID IT AGAIN!!"); } } function findAndReplaceSrcImages(sourceHTML){ var str = sourceHTML for(var i = 0; i< aImagesSrcs.length; i++){ var filename = aImagesSrcs[i].replace(/^.*[\\\/]/, ''); str = str.replace(aImagesSrcs[i], "images/"+ filename); } return str; } //src : http://jsfiddle.net/TzVd3/2/ function grabHtml(elId) { var str ='';
var elHtml = str + findAndReplaceSrcImages(document.getElementById(elId).innerHTML);
var body = '';
var n = elHtml.search("

") + "

".length;
var output = [elHtml.slice(0, n), body, elHtml.slice(n)].join('') + "";
zip.file(newsletterName, output);
}

$( document ).ready(function() {
//if the page is loaded first grab all images sources
aImagesSrcs = $('#main').children('img').map(function(){
return $(this).attr('src');
}).get();

$("#download_btn").click( function(){
grabHtml("main");
grabImages();
});
});

Prototyping download zip