Adding Multiple Files into a Zip File not Working

左心房为你撑大大i 提交于 2020-01-25 10:14:07

问题


I'm using JSZip to add selected files into a single zip file. The issue is only the last selected file is being added to the zip (which is also corrupted), see code below:

var zip = new JSZip();
var items = '';
var count = 0;
var zipName = 'resources.zip';

$$('input[type=checkbox]').each(function(e){

    if(e.checked){
        if(e.id!='select-all'){
            items = items + "'" + e.getAttribute('data-href') + "'|" + e.getAttribute('data-file') + ",";
        }
    }
});

if(items!=''){

    items = items.slice(0,-1)
    var tmp = items.split(',');

    for(i=0;i<tmp.length;i++){
        var item = tmp[i].split('|');
        var url = item[0];
        var filename = item[1];

        JSZipUtils.getBinaryContent(url, function (err, data) {
            if(err) {
                throw err; // or handle the error
            }
            zip.file(filename, data, {binary:true});
            count++;

            if(count == tmp.length) {

                zip.generateAsync({type:'blob'}).then(function(content) {
                    saveAs(content, zipName);
                });

            }

        });
    }

}

Can anyone see the issue with my code?


回答1:


Fixed it. Issue was I wasn't putting the urls into an array correctly.

Corrected line:

items.push(e.getAttribute('data-href') + '|' + e.getAttribute('data-file'));


来源:https://stackoverflow.com/questions/59780319/adding-multiple-files-into-a-zip-file-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!