From 2bf72226bc76a8de72155577065996e73f2df29e Mon Sep 17 00:00:00 2001
From: Xiao Gui <xgui3783@gmail.com>
Date: Thu, 27 Jun 2019 11:39:43 +0200
Subject: [PATCH] chore: avoid using b64 encoding and directly send file

---
 deploy/datasets/index.js                      | 10 +--
 src/services/zipFileDownload.service.ts       | 68 ++++++++-----------
 .../referenceToast.component.ts               |  4 +-
 3 files changed, 32 insertions(+), 50 deletions(-)

diff --git a/deploy/datasets/index.js b/deploy/datasets/index.js
index abb1ef174..80557fa3e 100644
--- a/deploy/datasets/index.js
+++ b/deploy/datasets/index.js
@@ -140,14 +140,8 @@ datasetsRouter.post("/downloadParcellationThemself", (req,res, next) => {
     })
   }
 
-  zip.generateAsync({type:"base64"})
-      .then(function (content) {
-        // location.href="data:application/zip;base64,"+content;
-        res.end(content)
-      });
-
-
-
+  res.setHeader('Content-Type', 'application/zip')
+  zip.generateNodeStream().pipe(res)
 });
 
 module.exports = datasetsRouter
\ No newline at end of file
diff --git a/src/services/zipFileDownload.service.ts b/src/services/zipFileDownload.service.ts
index 68131c4bf..35edeff6f 100644
--- a/src/services/zipFileDownload.service.ts
+++ b/src/services/zipFileDownload.service.ts
@@ -1,58 +1,44 @@
 import { Injectable } from "@angular/core";
-import {HttpClient} from "@angular/common/http";
-import {AtlasViewerConstantsServices} from "src/atlasViewer/atlasViewer.constantService.service";
-import {map} from "rxjs/operators";
+import {AtlasViewerConstantsServices} from "src/atlasViewer/atlasViewer.constantService.service"
 
 @Injectable({ providedIn: 'root' })
 export class ZipFileDownloadService {
 
-    constructor(private httpClient: HttpClient, private constantService: AtlasViewerConstantsServices) {}
+    constructor(private constantService: AtlasViewerConstantsServices) {}
 
+    /**
+     * TODO make naming more generic
+     */
     downloadZip(publicationsText, fileName, niiFiles) {
         const correctedName = fileName.replace(/[|&;$%@"<>()+,/]/g, "")
-        return this.httpClient.post(this.constantService.backendUrl + 'datasets/downloadParcellationThemself', {
-                fileName: correctedName,
-                publicationsText: publicationsText,
-                niiFiles: niiFiles === 0 ? null : niiFiles
-            },{responseType: "text"}
-        ).pipe(
-            map (data => {
-                this.downloadFile(data, correctedName)
-            })
-        )
-    }
-
-    downloadFile(data, fileName) {
-        const contentType = 'application/zip';
-        const b64Data = data
-
-        const b64toBlob = (b64Data, contentType='', sliceSize=512) => {
-            const byteCharacters = atob(b64Data);
-            const byteArrays = [];
-
-            for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
-                const slice = byteCharacters.slice(offset, offset + sliceSize);
-
-                const byteNumbers = new Array(slice.length);
-                for (let i = 0; i < slice.length; i++) {
-                    byteNumbers[i] = slice.charCodeAt(i);
-                }
-
-                const byteArray = new Uint8Array(byteNumbers);
-                byteArrays.push(byteArray);
-            }
-
-            const blob = new Blob(byteArrays, {type: contentType});
-            return blob;
+        const body = {
+            fileName: correctedName,
+            publicationsText: publicationsText,
+            niiFiles: niiFiles === 0 ? null : niiFiles
         }
+        const url = `${this.constantService.backendUrl}datasets/downloadParcellationThemself`
+
+        return fetch(url, {
+            method: 'POST',
+            headers: {
+                'Content-Type': 'application/json'
+            },
+            body: JSON.stringify(body),
+        })
+        .then(res => res.blob())
+        .then(data => {
+            this.simpleDownload(data, correctedName)
+        })
+    }
 
-        const blob = b64toBlob(b64Data, contentType);
+    simpleDownload(data, filename) {
+        const blob = new Blob([data], { type: 'application/zip'})
         const url= window.URL.createObjectURL(blob);
         const anchor = document.createElement("a");
-        anchor.download = fileName + '.zip';
+        anchor.download = filename + '.zip';
         anchor.href = url;
         anchor.click();
     }
 
-
+    
 }
\ No newline at end of file
diff --git a/src/ui/referenceToast/referenceToast.component.ts b/src/ui/referenceToast/referenceToast.component.ts
index 6ac648540..36cc042d0 100644
--- a/src/ui/referenceToast/referenceToast.component.ts
+++ b/src/ui/referenceToast/referenceToast.component.ts
@@ -85,7 +85,9 @@ export class ReferenceToastComponent implements OnInit{
         this.zipFileDownloadService.downloadZip(
             publicationsText,
             fileName,
-            this.parcellationNifti? this.parcellationNifti : 0).subscribe(data => {
+            this.parcellationNifti? this.parcellationNifti : 0
+        )
+        .then(() => {
             this.downloadingProcess = false
         })
         publicationsText = ''
-- 
GitLab