Adding images from url to zip file using jsZip

I am trying to create a zip file using jsZip. The contents of the zip file are images from the Internet. I have created the following code. But when I run all this, I get an empty mail file of 22 KB in size.

<html>
<head>
</head>
<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"></input>
</center>    
</body>    
</html>

(url1, url2 and url3 are replaced by the images I want to download).

Why am I getting these empty zip files?

+4
source share
1 answer

JSZipUtils.getBinaryContentis asynchronous: content will be added after the call zip.generate(). Before creating a zip file, you must wait for all the images.

Edit:

, , , HTTP-, Access-Control-Allow-Origin: server-hosting-the-page.com. Firefox Chrome . js CORS (. ) .

+4

Source: https://habr.com/ru/post/1569744/


All Articles