How to read local ZIP in HTML5/Javascript using JSZip

In our previous post How to load local file in Javascript using HTML5 FileReader we showed how to read a local file using the HTML5 FileReader.

Based on this, it’s pretty easy to use *JSZip*to read a local ZIP file:

var reader = new FileReader();
reader.onload = function(ev) {
    JSZip.loadAsync(ev.target.result).then(function(zip) {
        // TODO Your code goes here. This is just an example.
        console.log(zip)
    }).catch(function(err) {
        console.error("Failed to open", filename, " as ZIP file:", err);
    })
};
reader.onerror = function(err) {
    console.error("Failed to read file", err);
}
reader.readAsArrayBuffer(fileInput.files[0]);

One example of what you can do using the JSZip object is to list the filenames inside the ZIP file:

var filename = fileInput.files[0].name;
var reader = new FileReader();
reader.onload = function(ev) {
    JSZip.loadAsync(ev.target.result).then(function(zip) {
        for(let [filename, file] of Object.entries(zip.files)) {
            console.log(filename);
        }
    }).catch(function(err) {
        console.error("Failed to open", filename, " as ZIP file:", err);
    })
};
reader.onerror = function(err) {
    console.error("Failed to read file", err);
}
reader.readAsArrayBuffer(fileInput.files[0]);

Full example

<html>
<body>
    <input type="file" id="myfile" onchange="onMyfileChange(this)" />

    <script src="https://unpkg.com/[email protected]/dist/jszip.js" type="text/javascript"></script>
    <script type="text/javascript">
        function onMyfileChange(fileInput) {
            if(fileInput.files[0] == undefined) {
                return ;
            }

            var filename = fileInput.files[0].name;
            // var filesize = fileInput.files[0].size;
            var reader = new FileReader();
            reader.onload = function(ev) {
                JSZip.loadAsync(ev.target.result).then(function(zip) {
                    console.log(zip)
                }).catch(function(err) {
                    console.error("Failed to open", filename, " as ZIP file");
                })
            };
            reader.onerror = function(err) {
                console.error("Failed to read file", err);
            }
            reader.readAsArrayBuffer(fileInput.files[0]);
        }
    </script>
</body>
</html>