Angular 4.3:使用新的HttpClient获取一个arraybuffer [英] Angular 4.3: Getting an arraybuffer with new HttpClient
本文介绍了Angular 4.3:使用新的HttpClient获取一个arraybuffer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想更改为新的HttpClient.到目前为止,我处理以下文件下载:
I would like to change to the new HttpClient. Until now I handle file downloads the following:
getXlsx (): Observable<any> {
return this.http.get('api/xlsx', {
responseType: ResponseContentType.ArrayBuffer, // set as ArrayBuffer instead of Json
})
.map(res => downloadFile(res, 'application/xlsx', 'export.xlsx'))
.catch(err => handleError(err));
}
export function downloadFile(data: any, type: string, filename: string): string {
const blob = new Blob([data._body], { type });
const url = window.URL.createObjectURL(blob);
// create hidden dom element (so it works in all browsers)
const a = document.createElement('a');
a.setAttribute('style', 'display:none;');
document.body.appendChild(a);
// create file, attach to hidden element and open hidden element
a.href = url;
a.download = filename;
a.click();
return url;
}
将responseeType更改为'arraybuffer'将导致文件为空.有任何解决方法的想法吗?
Changing the respondeType to 'arraybuffer' will result in empty files. Any ideas how to solve it?
推荐答案
所以Martin解决了我的问题:
So Martin has solved my issue:
getXlsx (): Observable<any> {
return this.http.get('api/xlsx', {
responseType: 'blob' // <-- changed to blob
})
.map(res => downloadFile(res, 'application/xlsx', 'export.xlsx'))
.catch(err => handleError(err));
}
export function downloadFile(blob: any, type: string, filename: string): string {
const url = window.URL.createObjectURL(blob); // <-- work with blob directly
// create hidden dom element (so it works in all browsers)
const a = document.createElement('a');
a.setAttribute('style', 'display:none;');
document.body.appendChild(a);
// create file, attach to hidden element and open hidden element
a.href = url;
a.download = filename;
a.click();
return url;
}
这篇关于Angular 4.3:使用新的HttpClient获取一个arraybuffer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文