Kay
Kay

Reputation: 19660

How to assign a blob to an image src using angular

I am fetching an image via a http request which returns a blob and i want to assign the blob returned to an image src.

http request:

   const options = {
        headers,
        responseType: 'blob' as 'json'
    };

    return this.httpClient.get(url, options)

component.ts

async ngOnInit() {
   this.frontImageSrc = getImage()
}

async getImage() {
    const image = await this.service.imageRequest(id, "front", token).toPromise();
    var imageUrl = URL.createObjectURL(image)
    return imageUrl
}

component.html

  <img src={{frontImageSrc}} alt="image"/>

The image src does not get assigned and in the console i can see the following.

blob:http://localhost:4200/f846a3aa-8cd3-4876-8dd3-972c9469feb2 14:00:00.664 unsafe:blob:http://localhost:4200/f846a3aa-8cd3-4876-8dd3-972c9469feb2:1 GET unsafe:blob:http://localhost:4200/f846a3aa-8cd3-4876-8dd3-972c9469feb2 net::ERR_UNKNOWN_URL_SCHEME

Upvotes: 8

Views: 8058

Answers (1)

Blind Despair
Blind Despair

Reputation: 3295

Message about :unsafe stuff means that angular sanitised your url, because it considers it unsafe. Cleanest way to work this around is to introduce a pipe (although it is not necessary): like so:

@Pipe({ name: 'safeResourceUrl' })
export class SafeUrlPipe implements PipeTransform {
  constructor(private readonly sanitizer: DomSanitizer) {}

  public transform(url: string): SafeResourceUrl {
    return this.sanitizer.bypassSecurityTrustResourceUrl(url);
  }
}

Then in your component you can the following:

component.html

  <img [src]="frontImageSrc | safeResourceUrl" alt="image"/>

component.ts

async ngOnInit() {
   this.frontImageSrc = getImage()
}

async getImage() {
    const image = await this.service.imageRequest(id, "front", token).toPromise();
    var imageUrl = URL.createObjectURL(image)
    return imageUrl
}

ngOnDestroy() {
  URL.revokeObjectURL(this.imageUrl)
}

Of course you can do bypassing in your ngOnInit instead, but it's cleaner to use pipe. Also since url is created asynchronously it might make sense to do a null check in the template.

Upvotes: 13

Related Questions