I need to compress multiple txt files into a zip archive that are received in base64 format from a service response.
Here is the code snippet to download the zip file containing the compressed txt files stored under the "txt" folder:
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": represents an array of objects with various files, which are then compressed within the "txt" folder of the zip file. The property "item.name" refers to the file name within the array of objects.
I have encountered two issues:
1. Dynamic naming for the zip file
I am trying to assign a dynamic name to the zip file by storing it in a class attribute named "fileZipName" (the value of fileZipName is assigned during the onInit event of the component).
zip.generateAsync({type:"blob"})
.then(function(content) {
// see FileSaver.js
FileSaver.saveAs(content, this.fileZipName);
});
However, when using the variable "fileZipName" within the "then" block, I encounter the following error in the browser console:
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. Adding files to the zip archive
When I provide a fixed name like "filesTxt.zip", everything works fine. The zip file is generated correctly with the "readme.txt" file included and the "txt" folder created. However, the problem arises as the "txt" folder appears empty without the expected compressed file inside.
The variable "base64[1]" contains the base64 encoding of the txt file: "VGVzdCBJbmZyYTEw". Decoding it online reveals the correct txt file contents.
No error messages are displayed.
Can anyone assist me with these issues? Thank you,