Angular2 显示 base64 图像 ERR_INVALID_URL

Thi*_*ker 4 angular

在我的模板中:

<h5>Image upload</h5>
<input type="file" accept="image/*" (change)="changeListener($event)">
<div *ngIf="image">
    <img [src]="'data:image/jpg;base64,' +image | safeHtml">
</div>
Run Code Online (Sandbox Code Playgroud)

在我的控制器中:

image: string='';

changeListener($event) : void {
    this.readThis($event.target);
}

readThis(inputValue: any): void {

    var file:File = inputValue.files[0];
    var myReader:FileReader = new FileReader();

    myReader.onloadend = (e) => {
        this.image = myReader.result;
        console.log(this.image)
    }
    myReader.readAsDataURL(file);
}
Run Code Online (Sandbox Code Playgroud)

safeHtml 是一个管道:

@Pipe({name: 'safeHtml'})
export class SafeHtml {
  constructor(private sanitizer:DomSanitizer){}

  transform(html) {
    return this.sanitizer.bypassSecurityTrustResourceUrl(html);
  }
}
Run Code Online (Sandbox Code Playgroud)

但是,上传图像后ERR_INVALID_URL出现错误。不过,我可以在我的开发人员控制台中看到 base64 字符串。出了什么问题?

Pie*_*Duc 5

结果 frommyReader.result已经包含该'data:image/jpg;base64,'字符串,因此您应该删除它:

<img [src]="image | safeHtml">
Run Code Online (Sandbox Code Playgroud)