Showing an image that have been received as a Blob object in Angular 5

This is how i do in Angular 9, downloading file from Rest and displaying.

image: SafeUrl | null = null;

constructor(private sanitizer: DomSanitizer, private api: ApiService) {}

download() {
    const mediaType = 'application/image';
    this.api.download(this.application.cover_photo_id).subscribe(value => {
      const blob = new Blob([value], { type: mediaType });
      const unsafeImg = URL.createObjectURL(blob);
      this.image = this.sanitizer.bypassSecurityTrustUrl(unsafeImg);
    }, error1 => {

    });
}

Api service

download(fileId: string) {
    return this.http.get(Constants.downloadFile + `${fileId}`, {
      responseType: 'blob'
    });
}

Display

<img [src]="image" class="img-fluid rounded" alt="Responsive image">

First try to bind img tag to a variable that will be the url of your picture. For example

<img [src]=imageUrl>

Then you need to use DomSanitizer

import { DomSanitizer } from '@angular/platform-browser';

constructor(private sanitizer:DomSanitizer)

to bypassSecurityTrust of your unsafeUrl and in your component when you retrieve the image you should create an url for the image like this

getImageFromService() {
    this.authService.getProfileImage().subscribe(data => {
        unsafeImageUrl = URL.createObjectURL(data);
        imageUrl = this.sanitizer.bypassSecurityTrustUrl(unsafeImageUrl);
    }, error => {
        console.log(error);
    });
}

This will create a temporary url of your image which you can use in your binding

Tags:

Angular