Angular 2 - make byte [] from Web Api as src image

I have an Angular 2 application that connects to the Api web server. There is an endpoint that returns the byte [] of the image, which is stored in the sql database. How can I display this as an image in Angular? I can change the Web Api or Angular application.

The endpoint of My Web Api looks like this:

[Route("api/profileimage/{userId}")] public byte[] Get(string userId) { var image = _profileImageService.GetProfileImage(userId); return image; } 

And my HTML Angular looks like this ...

 <img src="http://localhost:2116/api/ProfileImage/{{tile.UserId}}" width="100" height="100"/> 

What conversion needs to be done, or what should the api serve?

+3
source share
1 answer

Convert the image in Base64 to your server:

 [Route("api/profileimage/{userId}")] public string Get(string userId) { var image = _profileImageService.GetProfileImage(userId); return System.Convert.ToBase64String(image); } 

For ease of use, I created a new directive to encapsulate all the code that we need to receive and display the image:

 import {Directive, OnInit, Input} from '@angular/core'; import {Http} from '@angular/http'; import {BROWSER_SANITIZATION_PROVIDERS, DomSanitizationService} from '@angular/platform-browser'; @Directive({ selector: '[profile-image]', providers: [BROWSER_SANITIZATION_PROVIDERS], host: { '[src]': 'sanitizedImageData' } }) export class ProfileImageDirective implements OnInit { imageData: any; sanitizedImageData: any; @Input('profile-image') profileId: number; constructor(private http: Http, private sanitizer: DomSanitizationService) { } ngOnInit() { this.http.get("http://localhost:2116/api/ProfileImage/" + profileId) .map(image => image.text()) .subscribe( data => { this.imageData = 'data:image/png;base64,' + data; this.sanitzedImageData = sanitizer.bypassSecurityTrustUrl(imageData); } ); } } 

In your template, enable it like this:

 <img [profile-image]="tile.UserId" width="100" height="100" /> 

Remember to add the directive to the directives array of your component.


Plunker work, for example, using

+19
source

All Articles