Skip to content Skip to sidebar Skip to footer

Bind Image From Service In Angular 6

I have an endpoint that provides me an image based on certain parameter. It's not an image url, its a plain image. So when i hit the endpoint in postman, in response, i receive an

Solution 1:

You can find detailed steps on how to achieve this in this blog post -> https://blog.mikehodnick.com/angular-download-image-blob-and-bind-to-img/

TL;DR - The long and short of it is you need to do the following:

(Please note this was implemented using Angular 4.1.3)

  1. Get your image using http
  2. Set the response type to be BLOB so that we get the image in binary format
  3. Sanitize the blob response
  4. Assign the sanitized response to a member variable in your service.ts file
  5. Assign the member variable to the src attribute in your view in HTML
  6. Profit :D

Sample Code from the above-linked blog post:

view

<img [src]="imageData">

component

import { Component, OnInit } from '@angular/core';
import { Http, ResponseContentType } from '@angular/http';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
import 'rxjs/add/operator/toPromise';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {

  imageData: any;

  constructor(private http: Http, private sanitizer: DomSanitizer) {
  }

  ngOnInit() {
    const imageUrl = 'http://where.your.images/are/hosted.jpg';

    this.http.get(imageUrl, {
      responseType: ResponseContentType.Blob
    })
      .toPromise()
      .then((res: any) => {
        let blob = new Blob([res._body], {
          type: res.headers.get("Content-Type")
        });

        let urlCreator = window.URL;
        this.imageData = this.sanitizer.bypassSecurityTrustUrl(
            urlCreator.createObjectURL(blob));
      });
  }

}

Solution 2:

On Angular 6+ you could try this

On the service:

import { DomSanitizer } from '@angular/platform-browser';
import { HttpClient, HttpHeaders } from '@angular/common/http';

...

constructor(private http: HttpClient, private sanitizer: DomSanitizer) {
}

getFile(url: string): any {

  return this.http.get(url, {
    responseType: 'blob'
  })
  .pipe(
    map((res: any) => {
      const urlCreator = window.URL;
      return this.sanitizer.bypassSecurityTrustUrl(urlCreator.createObjectURL(res));
    })
 );
}

On the component:

const imgSrc: any;

downloadFile(uri) {
  this.service.getFile(uri).subscribe((res: any) => {
  this.imgSrc = res;
});

}

On the template:

<img id="myImg" [src]="imgSrc" alt="Attached file" style="width: 100%">
<button type="button" (click)="downloadFile('YourFile/Url')" id="imgBtn">

Post a Comment for "Bind Image From Service In Angular 6"