我想使用angular下载生成的xls文件,并根据响应头Content-Disposition设置文件名。
我使用的东西是
downloadFile(): Observable<any> {
var url= "http://somehting";
return this.http.get(url, { observe: 'response', responseType: 'blob' as 'json' });
}
然后在我的控制器中:
this.dataService.downloadFile().subscribe(
data => {
this.debug.msg("response:", JSON.stringify(data));
saveAs(data.body, "test.xlsx");
},
err => {
console.error(err);
alert("Problem while downloading the file.\n" + "[" + err.status + "] " + err.statusText);
}
);
不幸的是,响应头没有设置,正文也是空的。
response: {
"headers":{
"normalizedNames":{
},
"lazyUpdate":null
},
"status":200,
"statusText":"OK",
"url":"http://localhost:4200/MyEndpoint/GetDownload",
"ok":true,
"type":4,
"body":{
}
}
如果我将procedure更改为responseType:response.headers
,那么我可以获得文件的内容,但我不知道如何访问blob。我错过了什么吗?如果是这样,那是什么?
发布于 2020-05-12 00:10:47
基于其他堆栈溢出的posts...this适用于我
在服务器集头上
Response.Headers.Add("Access-Control-Expose-Headers", "content-disposition");
angular dataService定义的下载程序。重要的是将observable设置为HttpResponse
downloadFile(): Observable<HttpResponse<Blob>> {
var url = "http://host/GetDownload";
return this.http.get<Blob>(url, { observe: 'response', responseType: 'blob' as 'json' });
}
和控制器
this.dataService.downloadFile().subscribe(
data => {
var fileName = "report.xlsx";
const contentDisposition = data.headers.get('Content-Disposition');
if (contentDisposition) {
const fileNameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
const matches = fileNameRegex.exec(contentDisposition);
if (matches != null && matches[1]) {
fileName = matches[1].replace(/['"]/g, '');
}
}
saveAs(data.body, fileName);
},
err => {
console.error(err);
this.blockUI.stop();
alert("Problem while downloading the file.\n"+
"["+err.status+"] "+err.statusText);
});
}
https://stackoverflow.com/questions/61733551
复制相似问题