Angular 2 – 从Web Api渲染byte 作为图像src

我有一个Angular 2应用程序连接到Web Api后端。 有一个端点返回存储在sql数据库中的图像的byte []。 如何在Angular中将其显示为图像? 我可以更改Web Api或Angular应用程序。

我的Web Api端点看起来像这样……

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

我的Angular HTML看起来像这样……

  

我需要做什么转换,或api应该提供什么?

将图像转换为服务器上的Base64:

 [Route("api/profileimage/{userId}")] public string Get(string userId) { var image = _profileImageService.GetProfileImage(userId); return System.Convert.ToBase64String(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); } ); } } 

在您的模板中包含如下:

  

不要忘记将指令添加到组件的directives数组中。


工作Plunker例如用法

因此rinukkusu接受的答案非常有用且详细, 但您不必:

1-既不制定指令(但你当然可以)

2-也不使用消毒剂服务并进行消毒例外

我对这两项任务有点不知所措,特别是绕过了消毒,所以我会写出最简单的方法来安全地处理这个问题。

您可以简单地使用以下方法(以通用方式):

1-将图像作为base64编码的字符串从后端返回

2-在Angular 2+中接收图像的base64字符串并在您的打字稿文件中构建以下字符串属性,然后在不使用清理服务的情况下直接在html中安全地使用它

 // so for example you will get the image for example in this dataService.ts this.http.get(this.api_url + 'image').subscribe(response => { this.image = response['image']; this.imageSrc = 'data:image/jpeg;base64,' + this.image; }); 

然后在你的html文件中,你可以直接使用imageSrc属性(例如从已经准备好属性的注入dataService)

  

我希望这可以帮助别人并非常感谢rinukkusu,因为他的回答帮助了我个人