在Angular4中,經過input:file上傳選擇圖片本地預覽的時候,經過window.URL.createObjectURL獲取的url賦值給image的src出現錯誤:javascript
<input type="file" (change)="fileChange($event)" > <img [src]="imgUrl" alt="">
import { Component, OnInit } from '@angular/core'; import { DomSanitizer } from '@angular/platform-browser' @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { imgUrl; constructor( private sanitizer: DomSanitizer ){} ngOnInit() { } fileChange(event){ let file = event.target.files[0]; let imgUrl = window.URL.createObjectURL(file); let sanitizerUrl = this.sanitizer.bypassSecurityTrustUrl(imgUrl); this.imgUrl = sanitizerUrl; } }