作者:Yao2524_420 | 来源:互联网 | 2023-01-12 02:02
我想换成新的HttpClient.到目前为止我处理文件下载如下:
getXlsx (): Observable {
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;
}
将respondeType更改为'arraybuffer'将导致空文件.任何想法如何解决?
1> Luke..:
所以马丁解决了我的问题:
getXlsx (): Observable {
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;
}