greggman / unzipit

Random access unzip library for JavaScript

Home Page:https://greggman.github.io/unzipit

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to unzip from a file upload?

inspiraller opened this issue · comments

commented

Hi

I have not found an example on your github README how to unzip a file and assumed I could do it with the same logic as a url.

This is my example:
https://codesandbox.io/s/hardcore-frog-ptq1q6?file=/src/index.js

I zipped up a json file like this:
{
"myjson": {
"result": [
"1",
"3",
10
],
"x": true
}
}
Then uploaded via a file, but when running your code I get

zip: Object
comment: ""
commentBytes: Uint8Array
entries: Object
file.json: ZipEntry
_reader: BlobReader
blob: File
<constructor>: "BlobReader"
_rawEntry: Object
versionMadeBy: 20
versionNeededToExtract: 20
generalPurposeBitFlag: 0
compressionMethod: 8
lastModFileTime: 37987
lastModFileDate: 22167
crc32: 2958080259
compressedSize: 62
uncompressedSize: 98
fileNameLength: 9
extraFieldLength: 0
fileCommentLength: 0
internalFileAttributes: 1
externalFileAttributes: 32
relativeOffsetOfLocalHeader: 0
nameBytes: Uint8Array
name: "file.json"
extraFields: Array(0)
commentBytes: Uint8Array
comment: ""
name: "file.json"
nameBytes: Uint8Array
size: 98
compressedSize: 62
comment: ""
commentBytes: Uint8Array
compressionMethod: 8
lastModDate: Sun Apr 23 2023 18:35:06 GMT+0100 (British Summer Time)
isDirectory: false
encrypted: false
externalFileAttributes: 32
versionMadeBy: 20

How do I unzip it?

regards

You get a list of files in the zip file like this

  const {entries} = await unzip(file);

To list all the files

   console.log(Object.keys(entries).join('\n'));

entries is just a JavaScript object with name entry pairs. If your zip file had

somedata.json
notes.txt
image.jpg
elephant.glb

Inside then entries would be

{
  'somedata.json': entry,
  'notes.txt': entry,
  'image.png': entry,
  'elephant.glb': entry,
}

You can get the contents of any one of them like this

    const someData = await entries['somedata.json'].json();
    const notes = await entries['notes.txt'].text();
    const blob = await entries['image.png'].blob();
    const glb = await entries['elephant.glb'].arrayBuffer();
commented

That's it:
I've updated the codesandbox for reference.
https://codesandbox.io/s/hardcore-frog-ptq1q6?file=/src/index.js