How to uncompress file inside ZIP archive using HTML5 & JSZip
In our previous post How to read local ZIP in HTML5/Javascript using JSZip we provided an example of how to use JSZip to list files inside a local ZIP archive using HTML5.
This post will expand upon this in order to read the content of a file compressed inside a local ZIP archive file.
In this example, we’ll read a local ZIP file using HTML5 <input type="file">
and uncompress its content. We’ll read the word/document.xml
file, so you can upload any .docx
file to test that.
JSZip.loadAsync(ev.target.result).then(function(zip) {
zip.file("word/document.xml").async("ArrayBuffer").then(function(data) {
// data is an ArrayBuffer
// TODO Your code goes here!
})
}).catch(function(err) {
console.error("Failed to open", filename, " as ZIP file:", err);
})
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 reader = new FileReader();
reader.onload = function(ev) {
JSZip.loadAsync(ev.target.result).then(function(zip) {
zip.file("word/document.xml").async("ArrayBuffer").then(function(data) {
// data is an ArrayBuffer
// TODO Your code goes here!
})
}).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]);
}
</script>
</body>
</html>