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?
var zip = new JSZip(); // Add a text file with the contents "Hello World\n" zip. file("Hello. txt", "Hello World\n"); // Add a another text file with the contents "Goodbye, cruel world\n" zip. file("Goodbye.
Add your jpg images to a folder, then right click on the folder and select Send to > Compressed (zipped) folder. You will end up with both the original and a zipped copy. Add your jpg images to a file, then CTRL-click on the file and select Create Archive. You will also find the option in the File menu.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With