【问题标题】:Error .zip containing multiple .pdf files using JSZip错误 .zip 包含使用 JSZip 的多个 .pdf 文件
【发布时间】:2020-05-09 18:57:14
【问题描述】:

不知道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 文件

【问题讨论】:

  • 您面临的问题是什么?

标签: javascript angular zip


【解决方案1】:

从这段代码 sn-p 开始。根据您的需要进行自定义。

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. 生成压缩文件的Blob
  4. 创建锚标记
  5. Blob 生成一个 URL
  6. 将 URL 添加到锚标记
  7. 以编程方式单击锚标记开始下载过程
  8. 删除网址

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-28
    • 2022-07-05
    • 1970-01-01
    • 1970-01-01
    • 2020-01-15
    • 1970-01-01
    相关资源
    最近更新 更多