Unable to download blob as file in Angular 7 from API
Asked Answered
C

1

7

I've been having some trouble getting file download working in my application. To download the file I made a new call in the API I am using to get data into the application. I've tested this API using Postman and it does seem to be working as I am able to download files with the call.

Unfortunately I am running into some issues with implementing it into my Angular application. When I call the function below I am getting a 'corrupt' file as it is unable to be opened. I have checked other questions/solutions related to my problem but after trying most of them I am getting no further.

The call in my service:

DownloadFile (companyId: string, fileId: string, extension: string, fileName: string): Observable<Blob> {
   const options = { responseType: 'blob' as 'json' }
   return this.http.get<Blob>(this.baseApiUrl + this.baseTag + "?companyId=" + companyId + "&fileId=" + fileId + "&extension=" + extension + "&fileName=" + fileName, options)
 }

Using the call of the service:

this.data.DownloadFile(this.company.id, selectedItem.id, this.getFileNameWithoutExtension(selectedItem.fileName), this.getExtensionFromFileName(selectedItem.fileName))
    .subscribe(resultBlob => 
      {
        //Success
        console.log('start download:', resultBlob);
        var blob = new Blob([resultBlob], { type: "application/pdf" } );
        saveAs(blob, selectedItem.fileName);
      },
    error => {
      //Error
      console.log(error);
    });

I am not seeing what is wrong with this part of my code.

Chloramphenicol answered 26/11, 2018 at 14:52 Comment(4)
Looks like you have flipped the filename and extension parameters in the call to data.DownloadFile()? Also, I'm curious why you are hard-setting the application type?Cantaloupe
Thank you! I was a little too hasty and the parameter switch up seemed to be it. If you post it as an answer I will mark it as correct.The hard coded application type was just for testing, it will be set dynamically so all stored files can be downloaded.Chloramphenicol
Ah, that makes sense. I also notice you use saveAs - good call, it works well across platforms including IOS.Cantaloupe
Saw it being used in another post, good to know it was a good choice!Chloramphenicol
C
2

In DownloadFile() the parameters are:

companyId, fileId, extension, fileName 

but when you call the service it looks like you have flipped the filename and extension parameters to:

companyId, fileId, fileName, extension

Easy mistake to make. :)

Cantaloupe answered 27/11, 2018 at 7:17 Comment(1)
Thanks a lot! Didn't notice it myselfChloramphenicol

© 2022 - 2024 — McMap. All rights reserved.