I have a .Zip file that is in memory as a File object. I want to access the individual files and add it to an array of File objects in memory. I see several options online but it all requires accessing a physical .zip file on a computer. How can I do it without saving it as a physical file?
You can certainly do this with JSZip, since File implements Blob you can probably just do JSZip.loadAsync(yourFileObject).then(zip => { /* do something */ }. See the docs. You'll want to iterate over every file in the archive and create blobs, optimally with Promise.all().
However, for way better performance and smaller size, I would like to point you to my library fflate. If you're trying to get an array of file objects in fflate:
// If you aren't using a bundler, see the CDN instructions in the docs
import { unzipSync, unzip } from 'fflate';
// multithreaded = false is slower and blocks the UI thread if the files
// inside are compressed, but it can be faster if they are not.
const getFiles = async (zipFile, multithreaded = true) => {
const zipBuffer = new Uint8Array(await zipFile.arrayBuffer());
const unzipped = multithreaded
? await new Promise((resolve, reject) => unzip(
zipBuffer,
(err, unzipped) => err
? reject(err)
: resolve(unzipped)
))
: unzipSync(zipBuffer);
const fileArray = Object.keys(unzipped)
.filter(filename => unzipped[filename].length > 0)
.map(filename => new File([unzipped[filename]], filename));
return fileArray;
}
console.log(someFileObject);
// File { ... }
getFiles(someFileObject).then(console.log)
// [File { ... }, File { ... }, ...]