这篇文章主要给大家介绍了关于Angular4实现图片上传预览路径不安全问题的解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧。

前言

前一段时间做项目时,遇到一个问题就是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中如何实现邮箱提示补全功能

以上就是使用Angular4有关图片路径不安全的问题的详细内容,更多请关注Work网其它相关文章!

09-06 08:19