2017-04-04 169 views
0

在我的模板:Angular2顯示的base64圖像ERR_INVALID_URL

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

而且在我的控制器:

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); 
} 

safeHtml是管道:

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

    transform(html) { 
    return this.sanitizer.bypassSecurityTrustResourceUrl(html); 
    } 
} 

然而,圖像上傳我後得到ERR_INVALID_URL錯誤。我可以在開發人員控制檯中看到base64字符串。出了什麼問題?

回答

3

myReader.result結果已經包含了'data:image/jpg;base64,'字符串,所以你應該刪除:

<img [src]="image | safeHtml"> 
+0

謝謝!那是錯誤 – Nitish