Angular Http客户端文件下载-响应中的文件名
我正在尝试从api url获取文件。我的目标是在输入文件字段中显示此文件(以前上载的文件)及其名称。目前,我已经创建了以下服务功能:Angular Http客户端文件下载-响应中的文件名,angular,Angular,我正在尝试从api url获取文件。我的目标是在输入文件字段中显示此文件(以前上载的文件)及其名称。目前,我已经创建了以下服务功能: getDocument(): Observable<Blob> { const request = this.documentUrl; return this.http.get(request, { responseType: 'blob' }); } 我得到一个按定义没有名字的斑点。我已经看到我可以将它转换成一个文件并给它命
getDocument(): Observable<Blob> {
const request = this.documentUrl;
return this.http.get(request, { responseType: 'blob' });
}
我得到一个按定义没有名字的斑点。我已经看到我可以将它转换成一个文件并给它命名,但是这个解决方案不适合我的需要。是否有一种方法可以从后端获取文件,或者是否有一种方法可以从具有原始名称的Blob中重建文件?请确保后端API在响应头中设置文件名。通常,文件名包含在
内容处置
标题中
例如:它看起来像内容配置:附件;filename=XYZ.csv
在angular中,可以按如下方式提取它:
.subscribe((response: HttpResponse<Blob>) => {
// Extract content disposition header
const contentDisposition = response.headers.get('content-disposition');
// Extract the file name
const filename = contentDisposition
.split(';')[1]
.split('filename')[1]
.split('=')[1]
.trim()
.match(/"([^"]+)"/)[1];
});
.subscribe((响应:HttpResponse)=>{
//提取内容处置标头
const contentDisposition=response.headers.get('content-disposition');
//提取文件名
const filename=contentDisposition
.split(“;”)[1]
.split('filename')[1]
.split('=')[1]
.trim()
.match(/”([^“]+)“/)[1];
});
您可以从响应标题中获取文件名How?能否提供一个示例?
.subscribe((response: HttpResponse<Blob>) => {
// Extract content disposition header
const contentDisposition = response.headers.get('content-disposition');
// Extract the file name
const filename = contentDisposition
.split(';')[1]
.split('filename')[1]
.split('=')[1]
.trim()
.match(/"([^"]+)"/)[1];
});