Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSZip extract file objects

I am extracting a zip file with JSZip by doing the following:

jszip.loadAsync(zipFile)
['then'](function(zip) {
    return bluebird.map(Object.keys(zip.files), function (filename) {
        // converts the compressed file to a string of its contents
        return zip.files[filename].async('string').then(function (fileData) {
            // fileData is a string of the contents
        })
    })
})

However, the output of this extraction is an array of strings of the file contents. I was wondering if it was possible to get an array of file objects as the output instead because I need the file object later.

I have tried to do

new File(fileData.split('\n'), filename)

But it loses the original file formatting.

Any suggestions?

like image 557
tgreen Avatar asked May 08 '26 00:05

tgreen


1 Answers

The File constructor takes a list of BufferSource (ArrayBuffer, Uint8Array, etc), Blob or string. If you split the content on \n, you will remove these \n. File will then concatenate each string without re-adding the new lines.

Use a blob instead:

return zip.files[filename].async('blob').then(function (fileData) {
    return new File([fileData], filename);
})
like image 177
David Duponchel Avatar answered May 09 '26 14:05

David Duponchel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!