Angular 7 get corrupted file while downloading blob

淺唱寂寞╮ 提交于 2020-07-03 04:57:40

问题


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:

The file is present in the response body:

Do you guys have any clues ?


回答1:


Try like this:

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


来源:https://stackoverflow.com/questions/58935037/angular-7-get-corrupted-file-while-downloading-blob

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!