Angular中如何通过API的Content-Disposition获取文件名并下载
实现从响应头Content-Disposition获取文件名下载文件
要替换固定下载文件名,改用API响应头中携带的文件名,需分两步修改代码:
1. 修改服务请求配置,获取完整响应(含响应头)
在shop.service.ts中,调整请求配置让HttpClient返回完整的HttpResponse对象,这样才能访问响应头信息:
import { Observable, HttpResponse } from '@angular/common/http'; // ... downloadWhitePaper(id: number, type: string): Observable<HttpResponse<Blob>> { const options = { responseType: 'blob' as 'blob', observe: 'response' as 'response' // 关键配置:获取包含头信息的完整响应 }; return this.httpClient.get<Blob>( `${this.apiUrl}/v1/sheets/downloads?category_id=${id}&type=${type}`, options ); }
2. 在组件中解析响应头,提取文件名完成下载
修改shop-detail.component.ts的downloadFile方法,解析响应头里的Content-Disposition字段,提取出真实文件名:
private downloadFile(type: string): void { const categoryId = this.productDetail.category_id; this.shopService.downloadWhitePaper(categoryId, type) .subscribe((res: HttpResponse<Blob>) => { // 解析Content-Disposition获取文件名 const contentDisposition = res.headers.get('Content-Disposition'); let filename = 'sample.docx'; // 兜底默认文件名 if (contentDisposition) { // 兼容两种格式:filename="xxx.docx" 或 filename=xxx.docx const filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/); if (filenameMatch?.[1]) { filename = filenameMatch[1].replace(/['"]/g, ''); } } this.blob = new Blob( [res.body!], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' } ); const downloadURL = window.URL.createObjectURL(this.blob); const link = document.createElement('a'); link.href = downloadURL; link.download = filename; // 使用解析得到的真实文件名 link.click(); window.URL.revokeObjectURL(downloadURL); // 释放URL对象,避免内存泄漏 }); }
注意事项
observe: 'response'是获取响应头的核心,默认HttpClient仅返回响应体,设置后才能拿到包含头信息的完整响应。- 正则解析逻辑兼容带引号和不带引号的文件名格式,覆盖常见的响应头写法。
- 最后调用
revokeObjectURL是推荐操作,避免长期占用浏览器内存。
内容的提问来源于stack exchange,提问作者vijay s
相关产品推荐
相关产品推荐

