Opening zip files in browser with FileReader and JSZip.js

P.Diddle picture P.Diddle · Jun 17, 2016 · Viewed 13k times · Source

I'm trying to open up zip files inside the browser with FileReader and JSZip.js, then handle the files contained inside. I can't figure out how to correctly pass the FileReader object to JSZip.

Here's a stripped version of the page I use to load the javascript:

<!DOCTYPE html>
<html>
<head>

<meta charset="UTF-8" />

<script type="text/javascript" src="zipscan.js"></script>
<script type="text/javascript" src="jszip.js"></script>
<script type="text/javascript" src="jquery-1.8.3.min.js"></script>

</head>
<body>

<div id="openFile"><input type="file" id="inputFile" /></div>

</body>
</html>

And the javascript in zipscan.js after removing all unnecessary code:

function checkFiles()
{ 
    //Check support for the File API support 
    if ( window.File && window.FileReader && window.FileList && window.Blob )
    {
        var fileSelected = document.getElementById( "inputFile" );
        fileSelected.addEventListener( "change", handleFile, false );
    } 
    else
    { 
        alert( "Files are not supported" ); 
    } 
}


function handleFile( evt )
{
    //Set wanted file object 
    var fileToRead = evt.target.files[0];

    //Create fileReader object
    var fileReader = new FileReader(); 
    fileReader.onload = function ( e )
    {
        //Create JSZip instance
        var archive = new JSZip().loadAsync( e.target );

        //Testing that it is loaded correctly
        alert( e.target );
        alert( archive.file( "hello.txt" ).name );
    } 
    fileReader.readAsArrayBuffer( fileToRead );
}

window.addEventListener( "load", checkFiles, false );

The first alert displays [object FileReader], and the second results in a TypeError, archive.file(...) is being null.

I have used FileReader's readAsText method with the same code to open text files successfully, so if there is an error it's either in using readAsArrayBuffer (JSZip documentation suggested it) or in the way I'm using it. Almost all the resources I've found about JSZip use the old method with constructor parameters instead of loadAsync so it could be I'm not using it right.

Answer

user1693593 picture user1693593 · Jun 17, 2016

You can pass a File object directly without the need to go via a FileReader. An File object is itself a (extended) Blob which JSZip can take as argument to loadAsync().

Working Example

f.onchange = function() {
  var zip = new JSZip();
  zip.loadAsync( this.files[0] /* = file blob */)
     .then(function(zip) {
         // process ZIP file content here
         alert("OK")
     }, function() {alert("Not a valid zip file")}); 
};
<script src="https://raw.githubusercontent.com/Stuk/jszip/master/dist/jszip.min.js">
</script>
<input type=file id=f>