首页 > 解决方案 > 错误 .zip 包含使用 JSZip 的多个 .pdf 文件

问题描述

我不知道 JSZip 库的用途,如果有了它你可以问我问的问题。

我的想法是这样的:

generateZip() {
const a = ['arraybase64example'];

const zip = new JSZip();

Array.from(a)
  .forEach(file => {
    zip.file("prueba", file)
  })

  return zip.generateAsync({
    type: 'arraybuffer', // changed from blob to arrayBuffer
    compression: 'DEFLATE',
    compressionOptions: {
      level: 9
    }
  }).then(function (content) {
    window.location.href = content; // Type 'ArrayBuffer' cannot be assigned to type 'string'
  });
}

我无法从浏览器下载与全局窗口对象相关的 .zip 文件。

标签: javascriptangularzip

解决方案


从这个代码片段开始。根据您的需要对其进行自定义。

const files = [{ name: "hello", content: "world" }]
const zipFile: JSZip = new JSZip()

files.forEach(file => zipFile.file<"string">(file.name, file.content))

zipFile.generateAsync<"blob">({ type: "blob" })
    .then(blob => {
        const a   : HTMLAnchorElement = this.renderer.createElement("a")
        const url = URL.createObjectURL(blob)

        this.renderer.setProperty(a, "href", url)
        this.renderer.setProperty(a, "download", "file.zip")

        a.click()
        URL.revokeObjectURL(url)
    })

解释

  1. 创建一个 zip 文件对象
  2. 将文件添加到对象
  3. 生成一个Blobzip文件
  4. 创建锚标记
  5. 生成一个 URLBlob
  6. 将 URL 添加到锚标记
  7. 以编程方式单击锚标记以开始下载过程
  8. 删除网址

注意 1:这里我使用了该Renderer2服务,因为我认为我们不应该直接与 DOM 交互。

注意 2:您需要在组件中注入Renderer2服务。


推荐阅读