0

I am looking for some direction on how to go about saving multiple files (currently on the client side as a base64 string) as a zip directory in Angular 2.

I am currently getting the files from my webapi as a base64 string. I convert the string to a byte[] for viewing using pdf-viewer. I also allow the user to save/print the pdf using file-saver.

Now, I would like to allow the user to download all selected files into a zip folder. Unfortunately, I don't fully understand blobs and such and therefore, need some assistance on how to approach this. Keep in mind, the object being returned from the webapi contains base64 strings for each file, but can be easily converted into a byte[] and blob.

Irrelevant_Coder
  • 231
  • 1
  • 5
  • 17

1 Answers1

0

For those that may find themselves in this position, the solution I came up with utilized my existing code and only required adding JSZip. The code for this:

public downloadAllFiles() {
    console.log("Downloading All Files");
    var fileName = this.defaultDataService.defaultDataBase + "-" + this.selectedYear.path + ".zip";
    var zip = new JSZip();

    var year = zip.folder(this.selectedYear.path);

    for (var i = 0; i < this.selectedTypes.length; i++) {            
        var subDir = year.folder(this.selectedTypes[i].path);
        for (var j = 0; j < this.selectedTypes[i].pdfList.length; j++) {
            subDir.file(this.selectedTypes[i].pdfList[j].name + ".pdf", this.createPdfBlob(this.convertBase64ToBytes(this.selectedTypes[i].pdfList[j].bytes)));
        }
    }

    zip.generateAsync({ type: "blob" })
        .then(function (blob) {
            FileSaver.saveAs(blob, fileName);
        });
}

convertBase64ToBytes(data: string) {
    let byteCharacters = atob(data);
    let byteNumbers = new Array(byteCharacters.length);

    for (var i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i);
    }

    let byteArray = new Uint8Array(byteNumbers);
    return byteArray;
}

createPdfBlob(src: any) {
    const byteArrays = [];
    byteArrays.push(src);
    return new Blob(byteArrays, { type: 'application/pdf' });
}
Irrelevant_Coder
  • 231
  • 1
  • 5
  • 17