我必须将几个txt文件压缩到一个zip中,这些压缩文件来自base64格式服务的响应。
这是在" txt“文件夹下下载压缩txt文件的zip的代码:
let zip = new JSZip();
zip.file("readme.txt", "Description content");
let txtFile = zip.folder("txt");
this.selectedItems?.forEach((item) => {
this.downloadService
.downloadFile(item.name)
.subscribe((response) => {
let base64 = response.output.split(",");
txtFile.file(item.name, base64[1], {base64: true});
});
});
zip.generateAsync({type:"blob"})
.then(function(content) {
// see FileSaver.js
FileSaver.saveAs(content, "fileTxt.zip");
});"selectedItems":是一个包含多个文件的对象数组,如果它们存在,将在zip文件的"txt“文件夹中压缩,而"item.name”则是具有文件名的对象数组的属性。
我有两个问题:
1.压缩文件的动态名称
我需要为zip文件添加一个动态名称。为此,我创建了一个类属性,其中存储名称" fileZipName“(fileZipName的值,在组件的onInit事件中分配它)。
zip.generateAsync({type:"blob"})
.then(function(content) {
// see FileSaver.js
FileSaver.saveAs(content, this.fileZipName);
});当在“然后”中使用变量"fileZipName“时,它将显示浏览器控制台中的以下错误:
core.js:6210 ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading 'fileZipName')
TypeError: Cannot read properties of undefined (reading 'fileZipName')2.向zip添加文件
如果我给它一个固定的名称,例如"filesTxt.zip“,它很好地工作,它正确地生成压缩文件,它在zip中包含"readme.txt”文件,它在zip中添加"txt“文件夹,但是在"txt”文件夹中没有显示我需要压缩的文件,文件夹"txt“是空的。
"base641",包含txt文件的base64代码:"VGVzdCBJbmZyYTEw",实际上,如果我去一个在线网站对其进行解码,它将正确返回txt文件。
我没有任何错误。
你能帮我一下吗?谢谢,
发布于 2022-04-28 09:14:03
对于第一个问题,我建议阅读添加JavaScript上下文以了解问题所在,但为了解决问题,只需将传统的函数表达式替换为箭头函数表达式,如下所示:
来自
zip.generateAsync({type:"blob"})
.then(function(content) {
// see FileSaver.js
FileSaver.saveAs(content, this.fileZipName);
});到
zip.generateAsync({type:"blob"})
.then((content) => {
// see FileSaver.js
FileSaver.saveAs(content, this.fileZipName);
});在第一个表达式中,this关键字不指向类实例(因此是undefined值),而在第二个表达式中,则是。
对于第二个问题,我从来没有使用过这个JSZip,但是从文档中我了解到,folder函数只会在输出压缩上创建一个文件夹。为了使用它的子文件,您需要自己添加它们。
let zip = new JSZip();
zip.file("readme.txt", "Description content");
// Option 1 (manually add all the files)
let txtFile = zip.folder("txt").file('file1.txt').file('file2.txt');
// Option 2 (add all subfiles indiscriminately) - Did not test this
let txtFile = zip.folder("txt").file(/.*/);https://stackoverflow.com/questions/72040481
复制相似问题