Html 如何在angular2中将Base64解码为图像

Html 如何在angular2中将Base64解码为图像,html,angular,Html,Angular,我需要将图像编码为Base64格式,然后将Base64值解码为图像,并在HTML页面中显示图像。现在我用下面的代码将一个图像编码到base64 getFiles(event) { this.files = event.target.files; //alert(this.files); var reader = new FileReader(); reader.onload = this._handleReaderLoaded.bind(this)

我需要将图像编码为Base64格式,然后将Base64值解码为图像,并在HTML页面中显示图像。现在我用下面的代码将一个图像编码到base64

getFiles(event) {
      this.files = event.target.files;
      //alert(this.files);
      var reader = new FileReader();
      reader.onload = this._handleReaderLoaded.bind(this);
      reader.readAsBinaryString(this.files[0]);
      //alert(this.files[0]);
  }

  _handleReaderLoaded(readerEvt) {
      var binaryString = readerEvt.target.result;
      this.filestring = btoa(binaryString);  // Converting binary string data.
     //alert(this.filestring);
      //console.log(this.filestring);
 }
我现在正在获取base64值。无法将base64值转换为图像

您可以尝试使用_sanitizer.bypassSecurityTrustUrl告诉angular src value是安全的。从角度来看这门课:

class DomSanitizationService {
sanitize(context: SecurityContext, value: any) : string
bypassSecurityTrustHtml(value: string) : SafeHtml
bypassSecurityTrustStyle(value: string) : SafeStyle
bypassSecurityTrustScript(value: string) : SafeScript
bypassSecurityTrustUrl(value: string) : SafeUrl
bypassSecurityTrustResourceUrl(value: string) : SafeResourceUrl
}
作为安全html的一个例子:

导出类AppComponent{

private _htmlProperty: string = '<input type="text" name="name">';

public get htmlProperty() : SafeHtml {
   return this._sanitizer.bypassSecurityTrustHtml(this._htmlProperty);
}

constructor(private _sanitizer: DomSanitizationService){}
private\u htmlProperty:string='';
public get htmlProperty():SafeHtml{
返回此.\u sanitizer.bypassSecurityTrustHtml(此.\u htmlProperty);
}
构造函数(私有_sanitizer:DomainSanitizationService){}

}

获得了以下代码的输出:

<img [src]="'data:image/jpg;base64,'+filestring" style="height:500px;width:500px" />


我认为您还应该能够将图像的src设置为基本64字符串。不要忘记添加
数据:image/jpeg;base64,
在base64字符串前面

我认为您还应该能够将图像的src设置为base64字符串。不要忘记添加
数据:image/jpeg;base64,
在您的base64字符串前面是的,我忘了添加它。现在正在工作。@BrianM