Reputation: 107
I would like process a quite large ZIP file, in which I just would like to extract some PDF files and then upload them to a server. I already have in my app a function that takes an Array of File, send them and get the results of the processing from the server.
My concern is how to set up an equivalent Array of File from the ZIP.
I have tested both zip.js and jszip.js, but I got some strange results. Here is my code with jszip
async function unzipAndSelect( zipFile ) {
var flist = [];
var zip = await JSZip.loadAsync(zipFile);
await zip.forEach( async function (relativePath, zipEntry) {
var match = zipEntry.name.match( /REGEX.pdf$/ );
if(match) {
var blob = await zip.file( zipEntry.name ).async("blob");
var file = new File( [blob], zipEntry.name, {type : 'application/pdf'} );
flist.push( file );
}
});
console.log( fileList );
return flist;
}
uploadPDFs( fileList ) {
if(fileList.length) {
fileList.forEach( function(f) {
// upload stuff ...
}
}
}
var fileList = unzipAndSelect( "myfile.zip" );
uploadPDFs( fileList );
The fileList seems to be populated but its length remains at zero. When I remove the test on the length, nothing happens. Is my approach correct ? Any help on what happens ?
Upvotes: 1
Views: 2611
Reputation: 107
I have looked at the JSZip internals and, as suggested by @patrick-evans, confirmed that the forEach()
method was not Promise aware.
Here is my solution :
async function unzipAndSelect( zipFile ) {
var flist = [];
var zip = await JSZip.loadAsync(zipFile);
// async-forEach loop inspired from jszip source
for(filename in zip.files) {
if (!zip.files.hasOwnProperty(filename)) {
continue;
}
// Object key is the filename
var match = filename.match( /REGEX.pdf$/ );
if(match) {
var blob = await zip.file( filename ).async("blob");
var file = new File( [blob], filename, {type : 'application/pdf'} );
flist.push(file);
}
}
return flist;
}
Upvotes: 1