window.URL.createObjectURL[Angular 7/Typescript]

window.URL.createObjectURL[Angular 7/Typescript],angular,typescript,url,angular7,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].rep

我必须在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'})
}
getFile(fileId:string):可观察{
返回此.http.get(environment.API_URL+'/file/'+fileId,{observe:'response',responseType:'blob'})
}
我的IDE还在window.URL上触发“实例成员不可访问”。createObjectURL()

文件似乎是从服务器和控制台获取的,我可以看到调试打印“导航到blob://”,但随后下载提示没有显示

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


谢谢大家!

这是我的一个可行版本

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

我也有类似的问题。不使用
窗口
为我修复了它。作为参考,我的完整代码是:

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-使用URL.createObjectURL(Blob)而不使用“窗口”:

const blobUrl = URL.createObjectURL(myBlob);
3-通过以下方式绕过消毒剂(XSS)安全:

const safeblobUrl =  this.sanitizer.bypassSecurityTrustResourceUrl(blobUrl);
现在,您可以在绑定中使用此URL:

<audio [src]="safeblobUrl"></audio>

感谢您的回复!它似乎和我的代码很相似,不管怎样,我试过了,但仍然不起作用。。。我真的不明白为什么,同样的代码片段在其他项目上也能完美地工作。也许我弄乱了一些角度库(但我不这么认为…),我会尝试用npm清理。否则,我会努力做到这一点,而不会留下污点。