5 url typescript angular angular7
我必须在我的 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)
}
Run Code Online (Sandbox Code Playgroud)
其中 getFile() 是一个简单的 http 请求
getFile(fileId: string): Observable<any> {
return this.http.get(environment.API_URL + '/file/' + fileId, {observe: 'response', responseType: 'blob'})
}
Run Code Online (Sandbox Code Playgroud)
我的 IDE 还在 window.URL 上触发了“实例成员不可访问”。createObjectURL ()
文件似乎是从服务器和控制台获取的,我可以看到调试打印“导航到 blob://”,但随后没有显示下载提示。
我在另一个 Angular 项目(但版本 6)中使用了相同的方法,效果很好,我不明白为什么现在不再工作了。有什么建议吗?
谢谢!
我有类似的问题。留下window为我修复它。作为参考,我的完整代码是:
export class DownloadComponent {
@Input() content: any;
@Input() filename = 'download.json';
download() {
const json = JSON.stringify(this.content);
const blob = new Blob([json], {type: 'application/json'});
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = this.filename;
link.click();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9343 次 |
| 最近记录: |