简体   繁体   English

React:使用项目目录中的 JSZip 读取 Zip 文件

[英]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.我正在尝试读取 zip 文件,其中包含来自 React 项目目录的图像。

When I open the Zip file from <input type="file" /> , it works by taking the event.target.files[0] .当我从<input type="file" />打开 Zip 文件时,它通过获取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"示例:“./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.任何帮助表示赞赏。

the documentation seems pretty clear: the first argument to loadAsync is the zip file data, but you're passing it a string. 文档似乎很清楚: loadAsync的第一个参数是 zip 文件数据,但您传递的是一个字符串。

(and what you're tring to do won't work anyway. your React code is running in the browser and has no knowledge of filesystem paths or filenames.) (而且你想做的事情无论如何都行不通。你的 React 代码在浏览器中运行,并且不知道文件系统路径或文件名。)

Anyone coming across this can use JSZip-utils and write the following code遇到这种情况的任何人都可以使用JSZip-utils并编写以下代码

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);
               });
            });
         });
      });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM