angular4教程|Angular4实现图片上传预览路径不安全的问题解决

更新时间:2024-03-27    来源:php入门    手机版     字体:

【www.bbyears.com--php入门】

前言

前一段时间做项目时,遇到一个问题就是AngularJS实现图片预览和上传的功能,在Angular4中,通过input:file上传选择图片本地预览的时候,通过window.URL.createObjectURL获取的url赋值给image的src出现错误:

WARNING: sanitizing unsafe URL value

下面介绍一下解决方法:

html代码:


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

本文来源:http://www.bbyears.com/jiaocheng/144565.html