我必须在我的 Angular 7 项目中显示/下载一个 .pdf 文件,但我在使用 window.URL.createObjectURL 时遇到了一些问题。这是我做的:
this.userService.getFile(report.id).subscribe(
res => {
console.log(res)
const filename = res.headers.get('content-disposition').split(';')[1].split('=')[1].replace(/\"/g, '')
const blob = new Blob([res.body], { type: res.body.type })
const url = window.URL.createObjectURL(blob)
const a: HTMLAnchorElement = document.createElement('a') as HTMLAnchorElement
a.href = url
a.download = filename
window.document.body.appendChild(a)
a.click()
window.document.body.removeChild(a)
URL.revokeObjectURL(url)
},
err => {
console.log(err)
}
其中 getFile() 是一个简单的 http 请求
getFile(fileId: string): Observable<any> {
return this.http.get(environment.API_URL + '/file/' + fileId, {observe: 'response', responseType: 'blob'})
}
我的 IDE 还在 window.URL 上触发了“无法访问实例成员”。创建对象 URL ()
文件似乎是从服务器和控制台获取的,我可以看到调试打印“Navigate to blob://”,但是没有出现下载提示。
我在另一个 Angular 项目(但版本 6)中使用了相同的方法并且效果很好,我不明白为什么现在不再工作了。有什么建议吗?
谢谢!