角度文件下载,名称来自内容内容处置



我想使用 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":{
}
}

如果我将程序更改为响应类型:blob,那么我能够获取文件的内容,但我不知道如何访问response.headers。 我错过了什么吗,如果是这样的话,那是什么?

基于其他堆栈溢出帖子...这对我有用

在服务器设置标头上

Response.Headers.Add("Access-Control-Expose-Headers", "content-disposition");

角度数据下载过程的服务定义。重要的是将可观察设置为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);
});
}

最新更新