我必须在我的Angular 7项目中显示/下载一个.pdf文件,但我在窗口方面遇到了一些问题。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还在窗口上触发"实例成员不可访问"。URLcreateObjectURL((
文件似乎是从服务器和控制台中提取的,我可以看到调试打印"导航到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();
}
}
您应该考虑以下项目:
1-确保您的Blob有效通过:
console.log(myBlob instanceof Blob); //true
如果不使用Blob构造函数来创建Blob。
2-使用不带"window"的URL.createObjectURL(Blob(:
const blobUrl = URL.createObjectURL(myBlob);
3-绕过Angular DomSanitizer(XSS(安全通过:
const safeblobUrl = this.sanitizer.bypassSecurityTrustResourceUrl(blobUrl);
现在您可以在绑定中使用此URL:
<audio [src]="safeblobUrl"></audio>