【发布时间】:2019-02-10 08:25:41
【问题描述】:
这应该很容易解决,但我知道我的想法无法找到解决方案。
我有一个这样的帖子:
getAccordo(filtro: Filter): Observable<Response> {
return this.http.post<Response>(`${this.ENDPOINT}/export`,
filtro,
{observe: 'response', responseType: 'blob' as 'json'}
)
.catch(error => this.handleError(error));
}
这就是我使用它的地方:
public getAccordo(event: any): any {debugger;
event.preventDefault();
this.accordiService.getAccordo(this.filter).subscribe(
res => {debugger;
const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
const anchor = document.createElement('a');
anchor.href = window.URL.createObjectURL(blob);
anchor.download = Utils.extractHeaders(res);
anchor.click();
},
error => {
console.log(error);
}
);
}
当我查看 chrome 控制台时,我可以看到标题中有一个 content-disposition: attachment; filename="esportazione_accordi_20180905.xlsx"
但在我的“res”中,这是缺失的。
id喜欢做的是获取文件名并在anchor.download中使用。
感谢您的帮助,如果您需要更多帮助,请随时询问。
编辑
这是我从响应标头中获得的标头,我什至没有看到其中 1 个:
我在服务器端添加了:.header("Access-Control-Expose-Headers", "content-disposition") 但还是不行
编辑2:
好的,我们越来越近了,我需要获取图片末尾的“文件名”值并将其分配给 anchor.download。
【问题讨论】:
-
响应标头被延迟解析 - 您需要实际尝试使用
res.headers.get('Content-Disposition')获取标头才能看到结果。 -
好的,所以如果我使用 res.headers.get('Content-Disposition') 我得到了一切,最后一步,我如何使用我需要的值?我会在一分钟内再次更新帖子以向您展示我的意思
-
您可以为此使用正则表达式 - 这是一个非常基本的示例:
const filename = /attachment; filename="(.+")/.exec(headerValue)[1];。这假设正则表达式将匹配 - 您可以在此处访问它的第二个数组元素之前检查exec调用null的返回值以确保此处安全。 -
Here 的另一个问题是关于文件名解析的问题。
标签: angular typescript http-post