[英]How to get the name of a file downloaded with Angular5
我的回应标题是:
HTTP/1.1 200 OK
Content-Disposition: attachment; filename="file.docx"
Accept-Ranges: bytes
Cache-Control: public, max-age=0
Last-Modified: Thu, 26 Apr 2018 10:37:00 GMT
ETag: W/"c61-16301871843"
Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document
Content-Length: 3169
Date: Thu, 26 Apr 2018 10:37:00 GMT
Connection: keep-alive
我试过这个代码,
public download(id: string): Observable<Blob> {
let headers = new Headers();
const _baseUrl = (Api.getUrl(Api.URLS.download));
headers.append('x-access-token', this.auth.getCurrentUser().token);
headers.append('sale_id', id);
return this.http.get(_baseUrl, { headers: headers, responseType: ResponseContentType.Blob})
.map((res) => {
console.log(res.headers) // show like in image
return new Blob([res.blob()], { type: 'application/octet-stream' })
});
}
没有显示 Content-Disposition !!
如何从标题中获取文件的名称?
您的后端需要返回一个特定的标头Access-Control-Expose-Headers
。 如果你不这样做,Angular 不会公开标题,解释为什么你看不到它。
你可以在这里找到更多信息(虽然它有点旧), 甚至更多信息在这里
希望这会节省您的时间,
首先将文件保护程序导入到 components.ts 文件中
import { saveAs } from 'file-saver';
return this.http.get(url, { headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
}, responseType: 'blob', observe: 'response' })
.pipe().subscribe({
next: (response: any) => {
let fileName = 'file';
const contentDisposition = response.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, '');
}
}
const fileContent = response.body;
const blob = new Blob([fileContent], { type: 'application/octet-stream' });
saveAs(blob, fileName);
},
error: (error) => {
this.handleError(error);
}
});
此外,设置 API 侧标头,如
'Access-Control-Expose-Headers', 'Content-Disposition'
尝试这个:
(res: Response) => {
const contentDisposition = res.headers.get('content-disposition') || '';
const matches = /filename=([^;]+)/ig.exec(contentDisposition);
const fileName = (matches[1] || 'untitled').trim();
return fileName;
};
实际上,angular 中的响应主体不会返回您可能需要的所有数据。 所以我们需要指定我们需要完整的响应。 为此,您需要在服务中添加带有observe: "response" as 'body' 的HTTPOptions,
var HTTPOptions = {
headers: new HttpHeaders({'Accept': 'application/pdf; charset=UTF-8',}),
observe: "response" as 'body',// to display the full response & as 'body' for type cast
'responseType': 'blob' as 'json'
}
return this.http.get(url, HTTPOptions);
然后你将能够得到完整的响应,通过订阅这个方法,
this.service.download().subscribe((result: HttpResponse<any>) => {
console.log(result);
console.log(result.headers.getAll('Content-Disposition'));
}, err => {});
您可以在Angular 文档中参考更多详细信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.