首页 > 解决方案 > React:使用 JSZip 从项目目录中读取 Zip 文件

问题描述

我正在尝试从 React 的项目目录中读取包含图像的 zip 文件。

当我从 中打开 Zip 文件时<input type="file" />,它通过获取event.target.files[0]. 但是当我将同一个文件放入反应项目中,然后尝试通过提供路径打开它时,它不起作用。

示例:“./test.zip”

我当前的代码:

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

我已经坚持了几个小时,文档也没有帮助。任何帮助表示赞赏。

标签: javascriptreactjsjszip

解决方案


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

推荐阅读