Unable to download blob as file in Angular 7 from API

Mikey123 picture Mikey123 · Nov 26, 2018 · Viewed 8.6k times · Source

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.

Answer

dmcgrandle picture dmcgrandle · Nov 27, 2018

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. :)