getting type [object object] in file content while downloading file, instead of blob using angular 7

Viewed 573

Using Angular 7, I am calling API by get method and try to download file by using 'saveAs' function from the fileSaver library.

when I getting filename from response header then unable to download the proper file and getting[Object object] in the file content but whenever using dummy name it Works fine.

it is component file:

         fileName:string="";
         const MIME_TYPE ={
         XLSX:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
         TXT:'text/*',
         PDF:'application/pdf'
         }
         downloadFile(){
           this.DownloadService.downloadFile(
          (data: any) => {
           this.fileName=data.headers.get('fileName');
            const EXT = this.fileName.substr(this.fileName.lastIndexOf('.')+1);
            saveAs(new Blob([data],{type:MIME_TYPE[EXT]}),this.fileName);
          }
        );
    }

DownloadService file

  public downloadFile(callback: (responseData: any) => void): void {
        this.apiService.downloadFile.subscribe((data: any) => {
          if (callback) {
            callback(data);
          }
        });
      }

apiService file

  downloadFile(param: any): Observable<any> {
          return this.http.get(api/download, {responseType:'blob',observe: 'response' });
        }

Output in file content

[Object object]
1 Answers

So there are a few things to consider.

  1. In some cases you may need to use JSON.Stringify() on the binary data before creating the new Blob if the blob type is HTML/TXT.

  2. If you are using Base 64 encoding you need to encode on the server and parse the response on the front end (the code for that is here).

export const base64ToArrayBuffer = (base64) => {
    const binaryString = window.atob(base64);
    const bytes = new Uint8Array(binaryString.length);
    return bytes.map((byte, i) => binaryString.charCodeAt(i));
};

  1. Another thing to consider are the Headers that are sent by the server that returns the file. Some HTTP requests may not be set up to handle the response correctly and could be sending incorrect Headers. Packages like Axios depend on these headers to parse the response correctly. To prevent this disconnect you may need to set the "responseType" to "blob".

Hope this helps any time travelers from the future.

Related