首页 > 解决方案 > 使用 DomSanitizer 后拒绝加载图像

问题描述

我有一项从服务器加载图像的服务,我想在<img [src]="imageURL">标签中显示该图像。我使用DomSanitizer使该 URL 安全,但我仍然遇到不安全的错误并且图像未显示。

在我的file.service.ts我有这个功能:

downloadResource(downloadUrl: string): Observable<Blob> {
    return this.httpClient.get<Blob>(downloadUrl, {
      headers: new HttpHeaders({
        'accept': 'application/octet-stream',
        'content-type': 'application/json'}),
      responseType: 'blob' as 'json'
    });
  }

该功能适用​​于下载图像和其他文件。

然后,在我的image.component.ts我这样调用函数:

imageURL: any;

  constructor(private fileService: FileService, private domSanitizer: DomSanitizer ) { }

  ngOnInit() {
    this.fileService.downloadResource(downloadUrl)
    .subscribe(data => {
        const blob = new Blob([data], {type: 'application/octet-stream'});
        this.imageURL = this.domSanitizer.bypassSecurityTrustUrl(window.URL.createObjectURL(blob));
    });
  }

我的image.component.html看起来像这样:

<img [src]="imageURL">

我收到以下错误:

拒绝加载图像“blob:https://someurl.72726 ”,因为它违反了以下内容安全策略指令:“img-src * data:”。

我也试过了:bypassSecurityTrustResourceUrl但我遇到了同样的错误。

我错过了什么吗?

编辑:当我imageURL在控制台上打印时,我得到了这个:

SafeValue 必须使用 [property]=binding: blob: https://someurl.72726(参见http://g.co/ng/security#xss

标签: angulartypescript

解决方案


推荐阅读