简体   繁体   中英

How to display an image via an async base64 string in Angular

I use the http client from Angular to load a base64 string from the backend. As soon as the string is received, the image should be displayed in the view. I tried the code below, but Angular responded because the string cannot be loaded into the view due to XSS security policies.

public image$: ReplaySubject<string>  = new ReplaySubject(1);

public loadImage(): void {
  ...
  this.deviceService.getItem(deviceId, itemId).then((response) => {
    this.image$.next(response.imageString);
  }
}
<img [src]="(image$ | async)" />

So I tried to use the DomSanitizer to trust the string. If the string is static, this works fine, but I wasn't able to set it up properly for the async case.

public image: string = this.sanitizer.bypassSecurityTrustUrl("data:image/png;base64,...");
<img [src]="image" />

I tried a lot of things also via DOM or ViewChild, but I could not find a solution for my use case. How can I display an image from a base64 string that I get via an async call?

I'd suggest you several options:

Use custom pipe to transform your string to SafeResourceUrl

safe.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({
  name: 'safe'
})
export class SafePipe implements PipeTransform {
  constructor(private sanitizer: DomSanitizer) {}

  transform(url) {
    return this.sanitizer.bypassSecurityTrustResourceUrl(url);
  }
}

html

<img [src]="image$ | async | safe" />

Ng-run Example

Convert string to SafeResourceUrl manually

ts

image$: ReplaySubject<SafeResourceUrl> = new ReplaySubject(1);
...
this.image$.next(this.sanitizer.bypassSecurityTrustResourceUrl(response.imageString));

Ng-run Example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM