Jszip Files Can't Be Unzipped
I want to download multiple files in a zip file. When the zip file downloads and I try opening it, I get the following error on macos 'unable to expand test into downloads (Error 1
Solution 1:
reader.readAsText
is asynchronous: reader.onload
will be called after everything else.
In the following code:
for (...) {
reader.onload = function() {
// 3
};
reader.readAsText(...); // 1
}
// 2
You will loop on every item of your array and register a callback (1
), then continue outside of the loop (2
). Finally, when the file reader ends its job, 3
will be executed.
That's why adding a setTimeout
"fix" the issue: after 5 seconds, the callbacks ended and filled in the zip
object.
The fix: you could read asynchronously every blob and wait for all reads to end before calling zip.generateAsync
. There is an easier way: JSZip v3 reads blobs so you can directly add it.
Edit:
Assuming pages
is a FileList, you can do:
for(let i = 0; i < pages.length; i++) {
// here, pages[i] is a File (https://developer.mozilla.org/en-US/docs/Web/API/File)
zip.file(pages[i].name, pages[i]);
}
zip.generateAsync({type:"blob"}).then(function(blob) {...});
A File
is a specialized Blob
, so JSZip can read it to.
Post a Comment for "Jszip Files Can't Be Unzipped"