前言
前一段時間做項目時,遇到一個問題就是AngularJS實現圖片預覽和上傳的功能,在Angular4中,通過input:file
上傳選擇圖片本地預覽的時候,通過window.URL.createObjectURL
獲取的url賦值給image的src出現錯誤:
WARNING: sanitizing unsafe URL value
下面介紹一下解決方法:
html代碼:
<input type="file" (change)="fileChange($event)" > <img [src]="imgUrl" alt="">
其中,change方法會在每次選擇圖片后調用,image的src必須通過屬性綁定的形式,使用插值表達式同樣會出錯
ts代碼
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; } }
首先,引入DomSanitizer,然后在構造器里面注入,最重要的就是把window.URL.createObjectURL
生成的imgUrl通過santizer的bypassSecurityTrustUrl方法,將它轉換成安全路徑。
上面是我整理給大家的,希望今后會對大家有幫助。
相關文章:
vue+springboot如何實現單點登錄跨域問題(詳細教程)
詳細介紹javascript中常用工具類的封裝(詳細教程)
在vue中詳細介紹源碼入口文件(詳細教程)
詳細介紹幾種JavaScript編碼規范(詳細教程)
使用jQuery與vue如何實現拖動驗證碼功能
在JS中如何實現郵箱提示補全功能
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com