Search code examples
javascriptreactjsjszip

React: Read Zip file using JSZip from the project directory


I am trying to read a zip file which has images from the project directory in React.

When I open the Zip file from <input type="file" />, it works by taking the event.target.files[0] . But when I put that same file in react project and then try to open it by giving a path , it doesnt work.

Example : "./test.zip"

My current code:

let jsZip = new JSZip();
jsZip.loadAsync("./test.zip").then(function (zip) {
         let imagess = [];
         Object.keys(zip.files).forEach(function (filename) {
            zip.files[filename].async("base64").then(function (fileData) {
               const image = document.createElement("img");
               image.src = "data:image/*;base64," + fileData;
               document.querySelector(".unziped-container").appendChild(image);
            });
         });
      }); 

I have been stuck on this for hours and the documentation is not helping either. Any help is appreciated.


Solution

  • Anyone coming across this can use JSZip-utils and write the following code

    JSZipUtils.getBinaryContent("../path/file.zip", function (err, data) {
             if (err) {
                throw err;
             }
             const jsZip = new JSZip();
             jsZip.loadAsync(data).then(function (zip) {
                Object.keys(zip.files).forEach(function (filename) {
                   zip.files[filename].async("base64").then(function (fileData) {
                      const image = document.createElement("img");
                      image.src = "data:image/*;base64," + fileData;
                      const unziped = document.querySelector(".unziped-container");
                      unziped.appendChild(image);
                   });
                });
             });
          });