How to download an excel (xlsx) file using Angular 5 HttpClient get method with Node/Express backend?

两盒软妹~` 提交于 2019-12-03 20:49:48

Finally figured it out.

2 specific changes made this work.

Change # 1 - Setting responseType : 'blob' and defining the params and headers first and then using them in http.get. (http is nothing but an object of type HttpClient from angular/common/http that has been injected into the service class.

getappsecdesignfile ( token, tool5filepath ) : Observable<any>{

       console.log("In Service tool5filepath: ", tool5filepath);
       console.log("In Service token", token);
       console.log("In Service GET url: ", this.getappsecdesignfileurl);

       let encodedtool5filepath = encodeURIComponent(tool5filepath);
       console.log('Encoded File Path: ', encodedtool5filepath);

       let getfileparams = new HttpParams().set('filepath', encodedtool5filepath);
       let getfileheaders = new HttpHeaders().set('Accept', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').set('Authorization', token);

       return this.http.get(this.getappsecdesignfileurl, {responseType: 'blob', params: getfileparams, headers: getfileheaders});
   }

Change # 2 - Component code - FileSaver. For some reason type: 'application/vnd.ms-excel' did not work in FileSaver. Here the res is nothing but the response from the http.get call.

let blobtool5 = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
FileSaver.saveAs(blobtool5, 'Application_Security_Design.xlsx');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!