window.URL.createObjectURL [Angular 7 / Typescript]

时间:2018-10-28 18:30:00

标签: angular typescript url 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)
  }

其中getFile()是一个简单的http请求

getFile(fileId: string): Observable<any> {
   return this.http.get(environment.API_URL + '/file/' + fileId, {observe: 'response', responseType: 'blob'})
}

我的IDE也正在window.URL上触发“无法访问实例成员”。 createObjectURL ()

文件似乎是从服务器和控制台获取的,我可以看到调试打印“ Navigate to blob://”,但没有出现下载提示。

我在另一个Angular项目中使用了相同的方法(但版本6),并且效果很好,我不明白为什么现在不再工作。 有什么建议吗?

谢谢!

3 个答案:

答案 0 :(得分:0)

我有类似的问题。省略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 :(得分: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>

答案 2 :(得分:-2)

这是我的可行版本。

let link = document.createElement('a');
link.target = '_blank';
link.href = window.URL.createObjectURL(blob);
link.setAttribute("download", fileName);
link.click();