【发布时间】:2020-10-22 17:29:08
【问题描述】:
当我意识到我的 http 响应根本不包含任何标题时,我正试图下载一个从服务器作为字节数组发送的 csv 文件。我期待我的回复中有一个“内容处置”标头。
以前,我只使用 JSON 响应,因此从不费心寻找标头。
我已经阅读了许多解决类似问题的关于 SO 的答案。但是,与大多数 OP 不同的是,我从服务器传递了“content-disposition”标头,并且也公开了相同的标头。
这是标题映射在浏览器上的外观,清楚地显示标题集并正确显示
即使有来自服务器的响应,我在订阅块中得到的只是 json 数据(如果是 json 请求)和 Blob 对象(如果是 blob 请求)。根本看不到任何标题。
我还确保在我的代码中没有放置响应拦截器,这可能会提取标头。
下面是我正在使用的一些代码:
downloadFile(entity: string) {
return this.http.get(ApiUrlConstants.API_URL.PRICING_CSV_DOWNLOAD_URL + entity,
{ responseType: 'blob' }); // tried with arraybuffer too
}
接收到数据后,订阅会调用下面的方法。这是我期待标题的地方
public processBlobResponse(data: any): void {
const blob = new Blob([data._body], { type: data.headers.get('Content-Type') });
const contentDispositionHeader = data.headers.get('Content-Disposition');
if (contentDispositionHeader !== null) {
const contentDispositionHeaderResult = contentDispositionHeader.split(';')[1].trim().split('=')[1];
const contentDispositionFileName = contentDispositionHeaderResult.replace(/"/g, '');
const downloadlink = document.createElement('a');
downloadlink.href = window.URL.createObjectURL(blob);
downloadlink.download = contentDispositionFileName;
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(blob, contentDispositionFileName);
} else {
downloadlink.click();
}
}
}
我很确定我错过了一些东西。有什么想法吗?
【问题讨论】:
-
将
observe: 'response'添加到您的选项中:{ responseType: 'blob', observe: 'response' } -
@David 这为我解决了这个问题。同时,我相信在文档中应该很容易找到它;我很惊讶我访问过的众多答案中没有一个对此发出信号。
-
@David 如果您能将此作为答案发布,将不胜感激。
标签: angular browser download http-headers cors