1
2
3
4
5
6
7
8
9
10
xxx.subscribe( (res) => {

let file = new Blob([result.body], { type: result.body.type});
let link = this.renderer2.createElement('a');
let tempFile = window.URL.createObjectURL(file);
this.renderer2.setAttribute(link, 'href', tempFile);
this.renderer2.setAttribute(link, 'download', result.headers.get('Content-Disposition').split('filename=')[1]);
link.click();
window.URL.revokeObjectURL(tempFile); //手动释放内存,必须
})

服务层代码:

Angular post 中 需要加上 {responseType: 'blob', observe: 'response'} //observe 返回完整的返回体

1
2
3
4
exportData(body: any): Observable<HttpResponse<Blob>> {
let url = 'example.com/downloadApi';
return this.http.post(url, body, { responseType: 'blob' , observe: 'response'});
}