5

我必须在我的 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)中使用了相同的方法并且效果很好,我不明白为什么现在不再工作了。有什么建议吗?

谢谢!

4

3 回答 3

4

我有一个类似的问题。留给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();
  }
}
于 2019-06-20T10:42:00.677 回答
0

您应该考虑以下项目:

1-确保您的 Blob 有效 通过:

console.log(myBlob instanceof Blob); //true

如果不使用 Blob 构造函数来制作你的 Blob。

2- 使用没有“窗口”的 URL.createObjectURL(Blob):

const blobUrl = URL.createObjectURL(myBlob);

3- 绕过 Angular DomSanitizer (XSS) 安全性:

const safeblobUrl =  this.sanitizer.bypassSecurityTrustResourceUrl(blobUrl);

现在您可以在绑定中使用此 URL:

<audio [src]="safeblobUrl"></audio>
于 2021-01-09T18:20:54.017 回答
-2

这是我的一个可行版本。

let link = document.createElement('a');
link.target = '_blank';
link.href = window.URL.createObjectURL(blob);
link.setAttribute("download", fileName);
link.click();
于 2018-10-28T23:07:58.040 回答