Working with Files in TypeScript (Angular 8) has led me to Encode the files in Base64 using the code below:
private async convertToBase64(evidences: Array<EvidenceToDisplay>): Promise<Array<EvidenceToDownload>> {
const results: Array<EvidenceToDownload> = [];
for (const evidence of evidences) {
const evidenceToDownload: EvidenceToDownload = {
base64: null,
name: '',
extension: '',
};
const reader = new FileReader();
reader.onloadend = function() {
evidenceToDownload.base64 = reader.result;
};
reader.readAsDataURL(evidence.file);
evidenceToDownload.name = evidence.name;
evidenceToDownload.extension = this.getExtensionFromName(evidence);
results.push(evidenceToDownload);
}
return results;
}
The result is then obtained in another method as shown below:
public async downloadEvidences() {
const zip = new JSZip();
let consecutive = 1;
const allEvidences: Array<EvidenceToDisplay> = this.mergeEvidenceArray(this.manualEvidences, this.mobilityEvidences);
const evidencesToDownload: Array<EvidenceToDownload> = await this.convertToBase64(allEvidences);
console.log(evidencesToDownload);
for (let i = 0; i < evidencesToDownload.length; i++) {
console.log(evidencesToDownload[i].base64);
zip.file(EVIDENCE + DASH + consecutive + DOT + evidencesToDownload[i].extension, evidencesToDownload[i].base64,
{ binary : true, base64: true, compression : 'DEFLATE' });
consecutive++;
}
zip.generateAsync({type: 'blob'}).then(function(blob) {
FileSaver.saveAs(blob, 'test' + DOT + ZIP);
});
}
After observing the logs from the console, it became clear that there was a discrepancy between the initial and subsequent results. The issue seems familiar to cases involving "array.forEach" compared to a standard loop. Any idea why this might be happening?
To address the problem, I switched to encoding the file in binary instead of base64, eliminating the need for a file reader. This change helped resolve the inconsistency in logging results.
public async downloadEvidences() {
const zip = new JSZip();
let consecutive = 1;
const allEvidences: Array<EvidenceToDisplay> = this.mergeEvidenceArray(this.manualEvidences, this.mobilityEvidences);
for (let i = 0; i < allEvidences.length; i++) {
const extension = this.getExtensionFromName(allEvidences[i]);
const MIMEType = this.getMIMEtype(extension);
const blob = new Blob([allEvidences[i].file], { type: MIMEType });
zip.file(EVIDENCE + DASH + consecutive + DOT + extension, blob,
{ binary : true, compression : 'DEFLATE' });
consecutive++;
}
zip.generateAsync({type: 'blob'}).then(function(blob) {
FileSaver.saveAs(blob, 'test' + DOT + ZIP);
});
}
For additional insights, reading files asynchronously proved to be beneficial. Check out this resource: