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