Search code examples
angulartypescriptdownloadhttpclientfilesaver.js

Angular 7 get corrupted file while downloading blob


Using Angular 7, i am calling api by posting the url file and try to download it by using 'saveAs' function from the fileSaver library. The file is downloading but it cannot be opened because it's corrupted.

my call is the following:

var file_url = (response as any).headers['Location'] + 'files/Data.xlsx';
var filename = 'Data_' + this.getDateService.getDateFile() + '.xlsx';

const httpOptions = {
          headers: new HttpHeaders({
            'Content-Type': 'application/x-www-form-urlencoded'
          }),
          responseType: 'arraybuffer',
          observe: 'response'
        };

let downloadParameters = { filename: 'Data_' + this.getDateService.getDateFile() + '.xlsx', file: file_url }

this.downloadFileService.downloadFile(downloadParameters, httpOptions).subscribe(reponse => {

          var blob = new Blob([(response as any).body], { type: 'application/vnd.openxmlformat-officedocument.spreadsheetml.sheet' });
          saveAs(blob, filename);
})

What i tried:

  • switch the Type MIME application/vnd.openxmlformat-officedocument.spreadsheetml.sheet by application/octet-stream
  • switch the responseType arraybuffer by blob or blob as json

Below, the response headers from the service:

enter image description here

The file is present in the response body:

enter image description here

Do you guys have any clues ?


Solution

  • Try like this:

    this.downloadFileService.downloadFile(downloadParameters, { responseType: 'blob' }).subscribe(blob=> {
      saveAs(blob, filename);
    })