zip.js get filename in getData callback

683 views Asked by At

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.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? 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?

1

There are 1 answers

0
user3674647 On

I resolved this problem by wrapping the getData call in a separate function so that the correct pid was still available within each callback. Still seems like lacking functionality in 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);
            }
        });
    }
}