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,此时就没有问题了~