[英]How to properly download excel file with Angular2
這是我的服務代碼,它通過響應xls文件發出post請求:
exportInternalOrder(body) {
let user_token: string = this.sessionService.getToken();
let headers = new Headers();
headers.append('responseType', 'arraybuffer');
headers.append('Authorization', 'Bearer ' + user_token);
return this.http.post(this.config.exportInternalOrder, body,{
headers: headers
}).map(res => new Blob([res._body],{ type: 'application/vnd.ms-excel' }));
}
應該處理excel文件的響應。 這是調用它的代碼:
let objToSend = this.makeObjToSend(false);
this.reportingService.exportExcel(objToSend)
.subscribe(
data => {
this.exportData(data);
},
error => {
this.errorFilterMsg.push({ severity: 'error', detail: 'Report exporting has failed!' });
}
);
這是文件的保存(由於某種原因,window.open什么都不做):
exportData(data){
let blob = data;
let a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = 'fileName.xls';
document.body.appendChild(a);
a.click();
}
但該文件仍然保存為損壞的文件。 使用郵差和卷曲時,它就可以了。 任何幫助,將不勝感激。
responseType
不應該在headers
中設置,它是RequestOptionsArgs
對象的一部分,它在post
函數中作為第二個參數傳遞, RequestOptionsArgs
包含headers
, responseType
和其他,你可以在這里閱讀更多相關內容。 所以,你的代碼應該是這樣的:
import { ResponseContentType } from '@angular/http';
exportInternalOrder(body) {
let user_token: string = this.sessionService.getToken();
let headers = new Headers();
headers.append('Authorization', 'Bearer ' + user_token);
return this.http.post(this.config.exportInternalOrder, body,{
headers: headers,
responseType: ResponseContentType.Blob
}).map(res => new Blob([res._body],{ type: 'application/vnd.ms-excel' }));
}
我正在寫這篇文章..對於正在尋找Angular 2解決方案的文件下載功能的其他人來說,這將有所幫助。 下面的代碼對我有用。
import { ResponseContentType } from '@angular/http';
exportInternalOrder(body) {
let user_token: string = this.sessionService.getToken();
let headers = new Headers();
headers.append('Authorization', 'Bearer ' + user_token);
return this.http.post(this.config.exportInternalOrder, body,{
headers: headers,
responseType: ResponseContentType.Blob}).map(res => new Blob([res.blob()],{ type: 'application/vnd.ms-excel' }));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.