【问题标题】:window.URL.createObjectURL [Angular 7 / Typescript]window.URL.createObjectURL [Angular 7 / Typescript]
【发布时间】:2019-04-01 18:04:33
【问题描述】:

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

谢谢!

【问题讨论】:

    标签: angular typescript url angular7


    【解决方案1】:

    我遇到了类似的问题。省略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();
      }
    }
    

    【讨论】:

      【解决方案2】:

      您应该考虑以下项目:

      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>
      

      【讨论】:

        【解决方案3】:

        这是我的一个可行版本。

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

        【讨论】:

        • 感谢您的回复!它似乎与我的代码相似,无论如何我尝试过但仍然无法正常工作......我真的不明白为什么,同样的 sn-p 在其他项目上也能完美运行。也许我搞砸了一些角度库(但我不这么认为......),我会尝试用 npm 清理。否则我会尝试在没有 blob 的情况下实现这一目标。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-28
        • 1970-01-01
        • 1970-01-01
        • 2019-07-18
        • 2019-09-17
        • 2019-10-08
        相关资源
        最近更新 更多