简体   繁体   English

zip.js在getData回调中获取文件名

[英]zip.js get filename in getData callback

I'm loading a .zip file full of .pngs using zip.js, and then for each of the entries I'm setting an Image element's source to the Blob produced by getData: 我正在使用zip.js加载一个充满.png的.zip文件,然后为每个条目将Image元素的源设置为getData生成的Blob:

zip.createReader(new zip.BlobReader(zipFile), function(reader) {
    reader.getEntries(function(entries) {
        for (var i = 0; i < entries.length; i++) {
            var pid = entries[i].filename.replace('.png', '');
            var img = document.getElementById('MCImg_' + pid);
            if (img) {
                entries[i].getData(new zip.BlobWriter('text/plain'), function(data) {
                    // I need to know the filename associated with `data` here
                    // so I can know which `img` to set the src of
                })
            }
        }
        //reader.close();
    })
}, function(error) {
    console.log('error reading zip');
});

The getData callbacks don't occur in any predictable order, so how can I know what to do with the data produced if it isn't tied to any particular filename? getData回调不会以任何可预测的顺序发生,所以如果不将其绑定到任何特定的文件名,我如何知道如何data生成的data I feel like this should be a pretty common use case and an easy question to answer, but I've searched to no avail... 我觉得这应该是一个非常普遍的用例,并且是一个容易回答的问题,但是我搜索没有用……

Likewise, if I don't know when the last getData call has completed, how do I know when to close the reader? 同样,如果我不知getData一次getData调用何时完成,我如何知道何时关闭阅读器?

I resolved this problem by wrapping the getData call in a separate function so that the correct pid was still available within each callback. 我通过将getData调用包装在单独的函数中解决了此问题,以便在每个回调中仍然可以使用正确的pid Still seems like lacking functionality in zip.js. 似乎仍然缺少zip.js中的功能。

function loadImagesFromZip(bin) {
    var zipFile = zips[bin];
    if (!(zipFile))
        return;
    zip.createReader(new zip.BlobReader(zipFile), function(reader) {
        reader.getEntries(function(entries) {
            for (var i = 0; i < entries.length; i++) {
                var pid = entries[i].filename.replace('.png', '');
                loadImage(pid, entries[i]);
            }
        })
    }, function(error) {
        console.log('error reading zip');
    });
}

function loadImage(pid, entry) {
    var img = document.getElementById('MCImg_' + pid);
    if (img && !img.src) {
        entry.getData(new zip.BlobWriter('text/plain'), function(data) {
            if (img) {
                img.src = URL.createObjectURL(data);
            }
        });
    }
}

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

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