94

I want to display OpenOffice files, .odt and .odp at client side using a web browser.

These files are zipped files. Using Ajax, I can get these files from server but these are zipped files. I have to unzip them using JavaScript, I have tried using inflate.js, http://www.onicos.com/staff/iz/amuse/javascript/expert/inflate.txt, but without success.

How can I do this?

2
  • 8
    "no success" please be more specific, show us some code, show us some errors... we're here to help, not to guess.
    – OcuS
    Commented Jan 19, 2010 at 18:04
  • Basically I just called inflate function - data = zip_inflate(src); But I think this is meant for single file. If a zip files contain multiple files in a directory structure then what will be the content of "data". I do not know how to use this library.
    – user69260
    Commented Jan 19, 2010 at 18:10

8 Answers 8

63

I wrote an unzipper in Javascript. It works.

It relies on Andy G.P. Na's binary file reader and some RFC1951 inflate logic from notmasteryet. I added the ZipFile class.

working example:
http://cheeso.members.winisp.net/Unzip-Example.htm (dead link)

The source:
http://cheeso.members.winisp.net/srcview.aspx?dir=js-unzip (dead link)

NB: the links are dead; I'll find a new host soon.

Included in the source is a ZipFile.htm demonstration page, and 3 distinct scripts, one for the zipfile class, one for the inflate class, and one for a binary file reader class. The demo also depends on jQuery and jQuery UI. If you just download the js-zip.zip file, all of the necessary source is there.


Here's what the application code looks like in Javascript:

// In my demo, this gets attached to a click event.
// it instantiates a ZipFile, and provides a callback that is
// invoked when the zip is read.  This can take a few seconds on a
// large zip file, so it's asynchronous. 
var readFile = function(){
    $("#status").html("<br/>");
    var url= $("#urlToLoad").val();
    var doneReading = function(zip){
        extractEntries(zip);
    };

    var zipFile = new ZipFile(url, doneReading);
};


// this function extracts the entries from an instantiated zip
function extractEntries(zip){
    $('#report').accordion('destroy');

    // clear
    $("#report").html('');

    var extractCb = function(id) {
        // this callback is invoked with the entry name, and entry text
        // in my demo, the text is just injected into an accordion panel.
        return (function(entryName, entryText){
            var content = entryText.replace(new RegExp( "\\n", "g" ), "<br/>");
            $("#"+id).html(content);
            $("#status").append("extract cb, entry(" + entryName + ")  id(" + id + ")<br/>");
            $('#report').accordion('destroy');
            $('#report').accordion({collapsible:true, active:false});
        });
    }

    // for each entry in the zip, extract it. 
    for (var i=0; i<zip.entries.length;  i++) {
        var entry = zip.entries[i];

        var entryInfo = "<h4><a>" + entry.name + "</a></h4>\n<div>";

        // contrive an id for the entry, make it unique
        var randomId = "id-"+ Math.floor((Math.random() * 1000000000));

        entryInfo += "<span class='inputDiv'><h4>Content:</h4><span id='" + randomId +
            "'></span></span></div>\n";

        // insert the info for one entry as the last child within the report div
        $("#report").append(entryInfo);

        // extract asynchronously
        entry.extract(extractCb(randomId));
    }
}

The demo works in a couple of steps: The readFile fn is triggered by a click, and instantiates a ZipFile object, which reads the zip file. There's an asynchronous callback for when the read completes (usually happens in less than a second for reasonably sized zips) - in this demo the callback is held in the doneReading local variable, which simply calls extractEntries, which just blindly unzips all the content of the provided zip file. In a real app you would probably choose some of the entries to extract (allow the user to select, or choose one or more entries programmatically, etc).

The extractEntries fn iterates over all entries, and calls extract() on each one, passing a callback. Decompression of an entry takes time, maybe 1s or more for each entry in the zipfile, which means asynchrony is appropriate. The extract callback simply adds the extracted content to an jQuery accordion on the page. If the content is binary, then it gets formatted as such (not shown).


It works, but I think that the utility is somewhat limited.

For one thing: It's very slow. Takes ~4 seconds to unzip the 140k AppNote.txt file from PKWare. The same uncompress can be done in less than .5s in a .NET program. EDIT: The Javascript ZipFile unpacks considerably faster than this now, in IE9 and in Chrome. It is still slower than a compiled program, but it is plenty fast for normal browser usage.

For another: it does not do streaming. It basically slurps in the entire contents of the zipfile into memory. In a "real" programming environment you could read in only the metadata of a zip file (say, 64 bytes per entry) and then read and decompress the other data as desired. There's no way to do IO like that in javascript, as far as I know, therefore the only option is to read the entire zip into memory and do random access in it. This means it will place unreasonable demands on system memory for large zip files. Not so much a problem for a smaller zip file.

Also: It doesn't handle the "general case" zip file - there are lots of zip options that I didn't bother to implement in the unzipper - like ZIP encryption, WinZip encryption, zip64, UTF-8 encoded filenames, and so on. (EDIT - it handles UTF-8 encoded filenames now). The ZipFile class handles the basics, though. Some of these things would not be hard to implement. I have an AES encryption class in Javascript; that could be integrated to support encryption. Supporting Zip64 would probably useless for most users of Javascript, as it is intended to support >4gb zipfiles - don't need to extract those in a browser.

I also did not test the case for unzipping binary content. Right now it unzips text. If you have a zipped binary file, you'd need to edit the ZipFile class to handle it properly. I didn't figure out how to do that cleanly. It does binary files now, too.


EDIT - I updated the JS unzip library and demo. It now does binary files, in addition to text. I've made it more resilient and more general - you can now specify the encoding to use when reading text files. Also the demo is expanded - it shows unzipping an XLSX file in the browser, among other things.

So, while I think it is of limited utility and interest, it works. I guess it would work in Node.js.

6
  • 1
    I have an old version of one of the demos online, but I came here looking for updates. @Cheeso Would be interested in updated links when you have time.
    – geocodezip
    Commented Mar 4, 2013 at 2:39
  • There is now also an npm package unzip-stream which works well with the Node.js streams API. Commented Jul 18, 2019 at 9:31
  • 2
    Just got a flag claiming that the links are dead. Can you check this again, and put the code in your SO answer? You get 30,000 characters. If that's not enough, please post a second answer. It doesn't do any good for these links to keep going down.
    – Cody Gray
    Commented Jul 31, 2020 at 4:21
  • Why cant the code be in github instead of the dead links? Seems easier. Commented Jul 1, 2021 at 19:03
  • most of the links are dead links. Commented Nov 15, 2021 at 11:39
32

I'm using zip.js and it seems to be quite useful. It's worth a look!

Check the Unzip demo, for example.

2
  • I have JSON files with a base64 encoded JSON string in zip format inside them. I need that inner JSON object. Java's InflatorInputStream can unpack it on the server, so it actually is in zip format. However, when I pass the decoded base64 data from atob() to zip.js using the BlobReader, I get "Error while reading zip file." error. Visually the output from atob() is binary, so the BlobReader seems right, tried the TextReader anyway, it gives "File format is not recognized.". Any ideas?
    – enigment
    Commented Jul 14, 2018 at 17:04
  • Solved my problem in one line of code with pako pako.inflate(binaryData, { to: 'string' })
    – enigment
    Commented Jul 14, 2018 at 20:26
22

I found jszip quite useful. I've used so far only for reading, but they have create/edit capabilities as well.

Code wise it looks something like this

var new_zip = new JSZip();
new_zip.load(file);
new_zip.files["doc.xml"].asText() // this give you the text in the file

One thing I noticed is that it seems the file has to be in binary stream format (read using the .readAsArrayBuffer of FileReader(), otherwise I was getting errors saying I might have a corrupt zip file

Edit: Note from the 2.x to 3.0.0 upgrade guide:

The load() method and the constructor with data (new JSZip(data)) have been replaced by loadAsync().

Thanks user2677034

1
  • 1
    This method has been removed in JSZip 3.0, please check the upgrade guide. Commented Nov 17, 2019 at 13:32
8

If you need to support other formats as well or just need good performance, you can use this WebAssembly library

it's promised based, it uses WebWorkers for threading and API is actually simple ES module

How to use

Install with npm i libarchive.js and use it as a ES module.

The library consists of two parts: ES module and webworker bundle, ES module part is your interface to talk to library, use it like any other module. The webworker bundle lives in the libarchive.js/dist folder so you need to make sure that it is available in your public folder since it will not get bundled if you're using bundler (it's all bundled up already) and specify correct path to Archive.init() method.

import {Archive} from 'libarchive.js/main.js';

Archive.init({
    workerUrl: 'libarchive.js/dist/worker-bundle.js'
});

document.getElementById('file').addEventListener('change', async (e) => {
    const file = e.currentTarget.files[0];

    const archive = await Archive.open(file);
    let obj = await archive.extractFiles();
    
    console.log(obj);
});

// outputs
{
    ".gitignore": {File},
    "addon": {
        "addon.py": {File},
        "addon.xml": {File}
    },
    "README.md": {File}
}
0
4

I wrote "Binary Tools for JavaScript", an open source project that includes the ability to unzip, unrar and untar: https://github.com/codedread/bitjs

Used in my comic book reader: https://github.com/codedread/kthoom (also open source).

HTH!

0
2

If anyone's reading images or other binary files from a zip file hosted at a remote server, you can use following snippet to download and create zip object using the jszip library.

// this function just get the public url of zip file.
let url = await getStorageUrl(path) 
console.log('public url is', url)
//get the zip file to client
axios.get(url, { responseType: 'arraybuffer' }).then((res) => {
  console.log('zip download status ', res.status)
//load contents into jszip and create an object
  jszip.loadAsync(new Blob([res.data], { type: 'application/zip' })).then((zip) => {
    const zipObj = zip
    $.each(zip.files, function (index, zipEntry) {
    console.log('filename', zipEntry.name)
    })
  })

Now using the zipObj you can access the files and create a src url for it.

var fname = 'myImage.jpg'
zipObj.file(fname).async('blob').then((blob) => {
var blobUrl = URL.createObjectURL(blob)
0
2

2023 Answer

Since ~2020 in Chrome and ~2023 in Safari you can use the standard Compression Streams API. https://developer.mozilla.org/en-US/docs/Web/API/Compression_Streams_API

For example, here is how to unzip data made with Java's "DeflaterOutputStream":

let DecompressionStream = globalThis["DecompressionStream"];

export async function zipInflate(zip: Uint8Array): Promise<Uint8Array> {
    let ds = new DecompressionStream("deflate");
    let blob = new Blob([zip]);
    const decompressedStream = blob.stream().pipeThrough(ds);
    let blob2 = await new Response(decompressedStream).blob();
    let ab = await blob2.arrayBuffer();
    let arB = new Uint8Array(ab);
    return arB;
}

The above source is TypeScript. If you need JavaScript please just remove the type specifiers after the colons.

2
  • This does not work and produces a TypeError: The compressed data was not valid: incorrect header check. ZIP files are a container for multiple files that are usually compressed using Deflate, while the Compression Streams API only allows decompressing single files compressed using Deflate.
    – cdauth
    Commented Jul 17 at 22:18
  • @cdauth is 100% correct that a ZIP file is different from a deflated stream, and my answer is for deflated streams. When the OP asked the question standard Web API did not support inflating deflated streams but now it does. So my answer contains useful information that could help people with the OP's problem. Commented Jul 18 at 6:14
0

Inspired by the code in this article, I have created a basic zero-dependencies TypeScript solution that relies on the new Compression Streams API:

async function extractZipFile(zip: Uint8Array, fileName: string): Promise<Uint8Array | undefined> {
    const dataView = new DataView(zip.buffer);
    let index = 0;
    while (true) { // eslint-disable-line no-constant-condition
        const signature = dataView.getUint32(index, true);
        if (signature === 0x04034b50) { // local file
            const fileNameLength = dataView.getUint16(index + 26, true);
            const thisFileName = [...zip.slice(index + 30, index + 30 + fileNameLength)].map((b) => String.fromCharCode(b)).join("");
            const startsAt = index + 30 + fileNameLength + dataView.getUint16(index + 28, true);
            const compressedSize = dataView.getUint32(index + 18, true);
            if (thisFileName === fileName) {
                const compressionMethod = dataView.getUint16(index + 8, true);
                const buffer = zip.slice(startsAt, startsAt + compressedSize);
                if (compressionMethod === 0x00){
                    return buffer;
                } else if (compressionMethod === 0x08) {
                    return new Uint8Array(await new Response(new Blob([buffer]).stream().pipeThrough(new DecompressionStream("deflate-raw"))).arrayBuffer());
                } else {
                    throw new Error(`Unknown compression method 0x${compressionMethod.toString(16)}`);
                }
            } else {
                index = startsAt + compressedSize;
            }
        } else if (signature === 0x02014b50) { // central directory
            index += 46 + dataView.getUint16(index + 28, true) + dataView.getUint16(index + 30, true) + dataView.getUint16(index + 32, true);
        } else if (signature === 0x06054b50) { // end of central directory
            break;
        } else {
            throw new Error(`Unrecognized signature 0x${signature.toString(16)}`);
        }
    }
}

It takes a binary ZIP file and extracts a single file from it, identified by its file name. The file name should include its directory path, for example test/file.txt. The function returns the decompressed content of the file, or undefined if the ZIP file does not contain a file with the given name. If the ZIP file contains multiple files with that name, the first one is returned.

However, ZIP files can appear in a variety of shapes, and in particular, the above code will have trouble in the following scenarios:

  • Files inside a ZIP file can use a large variety of compression methods. The above code only supports the two most common ones, 8 (deflate) and 0 (no compression).
  • File names can be encoded in different ways. The above assumes ISO-8859-1 and will not work as expected when a different encoding is used.
  • ZIP64 is a variation of ZIP that supports larger files. The above code will fail to handle it.
  • Many ZIP files lack the compressed size metadata because their content was compressed on the fly, and instead list the compressed size in a data signature after each file and in the central directory at the end. The above code will fail to handle such files. The right way would be to parse the ZIP file from the end, guess where the central directory starts, and extract the compressed sizes from that.

As you can see, extracting a file from a ZIP file is very easy as long as you know the start and end position of the file and it is using no compression or one supported by the Compression Streams API. But there are lots of scenarios where this is not the case. Use the above code only if you are certain that the files provided will not fall into any of the edge cases listed above. Otherwise, use a library as recommended in many of the other answers.

Not the answer you're looking for? Browse other questions tagged or ask your own question.