javascript - 错误 .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)
})
解释
- 创建一个 zip 文件对象
- 将文件添加到对象
- 生成一个
Blob
zip文件 - 创建锚标记
- 生成一个 URL
Blob
- 将 URL 添加到锚标记
- 以编程方式单击锚标记以开始下载过程
- 删除网址
注意 1:这里我使用了该Renderer2
服务,因为我认为我们不应该直接与 DOM 交互。
注意 2:您需要在组件中注入Renderer2服务。
推荐阅读
- sql - 基于计数使用 HeidiSQL 删除记录
- java - spring boot feign 客户端返回“FileUploadException:请求被拒绝,因为没有找到多部分边界”
- swiftui - 升级到 Xcode 12 后,SwiftUI 列表视图有不同的颜色
- arrays - React .map 仅返回第一项
- android - 如何使用 FFmpeg for android 编译 OpenCV 4.4?
- android - 如何将downloadImageurl保存到firestore?
- python - 我怎样才能让“for循环”正常工作?
- scala - Scala Spark 使用 Window 函数查找最大值
- python-3.x - Catkin_make 找不到 Boost?
- python - 使用 2D 索引数组对 3D 数组值进行 Numpy 赋值