简体   繁体   English

Zip 由 JSZip 生成,仅包含单个图像文件

[英]Zip Generated by JSZip contains only single image file

I am trying to generate zip from images using JSZip.我正在尝试使用 JSZip 从图像中生成 zip。 But every time i get only single image in zip instead of 100 images.但是每次我在 zip 中只得到一个图像而不是 100 个图像。 Here is my code这是我的代码

   $("#download-images-small").on("click", function(){

        var zip = new JSZip();
        var count = 0;
        var zipFilename = "zipFilename.zip";
        var selections = $('.checkbox:checked')  //This returns an array of checkbox selected elements. 
        // Each checkbox contains URL in its data attribute ie. selections = ['url1', 'url2', 'url3'...]. See HTML Code.  

        for (var i = selections.length - 1; i >= 0; i--) {
            var filename = "filename"+ i +"."+ $(selections[i]).data("type");
            // loading a file and add it in a zip file
            console.log($(selections[i]).data("href"))
            JSZipUtils.getBinaryContent($(selections[i]).data("href"), function (err, data) {
               if(err) {
                  throw err; // or handle the error
               }
               zip.file(filename, data, {binary:true});
               count++;
               if (count == selections.length) {
                 zip.generateAsync({type:'blob'}).then(function(content) {
                      saveAs(content, zipFilename);
                   });
               }
            });
        }
    })

HTML code: HTML 代码:

<div class="fetched-images">
    <%= image_tag obj["url"], class: "img-fluid", title: obj["title"] , data:{ type: obj["ity"] }, crossOrigin: "Anonymous" %>
    <label class="checkbox-container">
        <input type="checkbox" data-type="<%= file_type %>" data-href="<%= file_url %>" checked="checked" class="this-image">
        <span class="checkmark"></span>
    </label>
</div>

Its quite simple.它很简单。

JSZipUtils.getBinaryContent calls a callback inside which you are appending filesto zip . JSZipUtils.getBinaryContent调用一个回调,您在其中将文件附加zip And since callbacks don't run in same context it doesn't have access to your updated filename variable and always takes the last assigned value (in your case filename0) and use this variable for each iteration hence rewriting the same file instead of adding new.并且由于回调不在同一上下文中运行,因此它无法访问您更新的filename变量,并且始终采用最后分配的值(在您的情况下为 filename0)并在每次迭代中使用此变量,因此重写同一个文件而不是添加新的. Call something which is unique inside the callback for filename.在文件名的回调中调用唯一的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM