Angular4圖片上傳預覽路徑不安全問題


在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方法,將它轉換成安全路徑。
最后將生成的安全的url賦值給imgUrl,此時就沒有問題了~

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM