【问题标题】:How do I use JSZip to unzip a .Zip File object in memory?如何使用 JSZip 解压缩内存中的 .Zip 文件对象?
【发布时间】:2021-11-08 08:26:07
【问题描述】:

我有一个 .Zip 文件作为 File 对象在内存中。我想访问各个文件并将其添加到内存中的文件对象数组中。我在网上看到了几个选项,但都需要访问计算机上的物理 .zip 文件。不保存为物理文件怎么办?

【问题讨论】:

  • 你是在浏览器还是节点中使用它?
  • 我认为是浏览器?我正在从 HTTP 响应创建 .zip 文件,并希望在 UI 上显示各个文件
  • JSZIp docs 做那件事。

标签: javascript zip jszip


【解决方案1】:

你当然可以用 JSZip 做到这一点,因为File 实现了Blob,你可能只做JSZip.loadAsync(yourFileObject).then(zip => { /* do something */ }。请参阅docs。您需要遍历存档中的每个文件并创建 blob,最好使用 Promise.all()

但是,为了获得更好的性能和更小的尺寸,我想将您指向我的库 fflate。如果您尝试在fflate 中获取文件对象数组:

// If you aren't using a bundler, see the CDN instructions in the docs
import { unzipSync, unzip } from 'fflate';

// multithreaded = false is slower and blocks the UI thread if the files
// inside are compressed, but it can be faster if they are not.
const getFiles = async (zipFile, multithreaded = true) => {
  const zipBuffer = new Uint8Array(await zipFile.arrayBuffer());
  const unzipped = multithreaded
    ? await new Promise((resolve, reject) => unzip(
        zipBuffer,
        (err, unzipped) => err
          ? reject(err)
          : resolve(unzipped)
      ))
    : unzipSync(zipBuffer);
  const fileArray = Object.keys(unzipped)
    .filter(filename => unzipped[filename].length > 0)
    .map(filename => new File([unzipped[filename]], filename));
  return fileArray;
}

console.log(someFileObject);
// File { ... }

getFiles(someFileObject).then(console.log)
// [File { ... }, File { ... }, ...]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-28
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 2023-03-21
    • 2017-09-28
    • 2018-06-19
    • 1970-01-01
    相关资源
    最近更新 更多