错误.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文件

从这个代码片段开始。根据您的需要进行定制。

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. 生成zip文件的Blob
  4. 创建定位标记
  5. 生成Blob的URL
  6. 将URL添加到锚点标记
  7. 以编程方式单击锚点标记以启动下载过程
  8. 删除URL

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

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

最新更新