10 Mar 2021

How to read zip file in Browser using JavaScript?


In this post we will talk about How to read zip file in Browser Using JavaScript? As you know that What is a zip file? Zip file used to compress the list of files data. It decreases the file size. And its becomes more easy to import data & saves internet connection board bandwidth if you are going to download any zipped file.

Reading Zipped Files Using JavaScript.

To read a zip file we are going to Use a JSZip JavaScript library.

How to import JSZip JavaScript library ?

To import JSZip library under your web projects, Just put CDN link to your webpage's head with script element.

JSZip CDN link
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.2.0/jszip.min.js"></script>
    

  • Get the [File Object] of zip file from InputHTMLElement with type attribute - file.
          <input type="file" id="inputFileId"/>
          
  • onchange event of input type file, gives a list of selected file.
  • Now call JSZip constructor. call loadAsync method over jszip object. which returns JavaScript [Promise Object].
    And the promise take executor function with one argument,
    Provided argument contains all the entries of Zipped Files.
    Next we call JSZip.forEach method; Loop Over iteratable object.
  • Beside calling JSZip.forEach method, you may call JSZip.file(name), Which returns ZipObject Object.
    name - should be known before calling, otherwise it return JavaScript Null Object.
  inputFileId.onchange = function (e){

 var file = e.target.files[0];



var new_zip = new JSZip();  

new_zip.loadAsync(file).then(function(zip) { 

//JSZip.forEach method applyed

zip.forEach( function (relativePath, zipObject){

  //work with zip entries
  
  zipe.async("base64", function (progress){
   //Return process progress value
}).then(function (data){
 //Here work with data
});

  
  
  });
  
});

}//onchange event
 


Reaction:

No comments:

No Comments

COMMENT FROM MESSAGE