【发布时间】:2019-04-10 22:36:02
【问题描述】:
我遇到了一个问题,但我找不到任何解决方案。因此,如果这个问题以某种方式与其他人重复,我提前道歉。
问题是我正在向后端发送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);
}
【问题讨论】:
标签: angular typescript