我遇到了一个问题,但找不到任何解决方案。因此,如果这个问题以某种方式重复了其他人,我先向您道歉。
问题是我正在向后端发送GET
请求并得到响应。响应正文中有Blob
。我尝试下载它,但是在获取文件名命名下载文件之前。在本地,一切正常。但是在外部版本中,文件不会下载。单击按钮后有响应,我看到我进入了FileUtil
中的保存功能。但是下载没有开始。有人知道是什么问题吗?
这是Chrome检查工具中“网络”标签中的响应(如您所见,所有标头都在接收中)
download.service.ts
downloadFile(id: string) {
return this.apiService.getFile(id).pipe(
map(response => {
const data = response.body;
const blob = new Blob([data], { type: 'application/zip' });
FileUtil.save(blob, this.getFileName(response.headers));
})
)
}
private getFileName(headers: HttpHeaders) {
const contentDisposition = headers.get('Content-Disposition') || '';
const matches = /filename=([^;]+)/ig.exec(contentDisposition);
const fileName = (matches[1] || 'file.zip').trim();
return fileName;
}
api.service.ts
getFile(id: string): Observable<HttpResponse<Blob>> {
return this.httpClient.get<Blob>(requestUrl, {responseType: 'blob' as 'json', observe: 'response'});
}
FileUtil.ts
static save(data: Blob, name: string) {
const a = document.createElement('a');
document.body.appendChild(a);
const url = window.URL.createObjectURL(data);
a.href = url;
const filename = name;
a.download = filename;
a.click();
setTimeout(() => {
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
}, 0);
}
答案 0 :(得分:0)
您可以尝试这样
FileUtil.ts
save(data: Blob, name: string) {
const a = document.createElement('a');
document.body.appendChild(a);
const blob = new Blob([data], { type: 'octet/stream' });
const url = window.URL.createObjectURL(data);
a.href = url;
a.download = "filename.csv"; // you need to write the extension of file here
a.click();
window.URL.revokeObjectURL(url);
})
}
答案 1 :(得分:0)
问题的原因丢失了('Access-Control-Expose-Headers', 'Content-Disposition')
,浏览器不知道我的回答是他应该下载的附件。因此,请两次检查响应的标题。