首页  >  文章  >  web前端  >  Angular图片上传预览路径问题的解决

Angular图片上传预览路径问题的解决

php中世界最好的语言
php中世界最好的语言原创
2018-04-13 15:09:212156浏览

这次给大家带来Angular图片上传预览路径问题的解决,解决Angular图片上传预览路径问题的注意事项有哪些,下面就是实战案例,一起来看一下。

前言

前一段时间做项目时,遇到一个问题就是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方法,将它转换成安全路径。

最后将生成的安全的url赋值给imgUrl,此时就没有问题了~

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

AngularJS实现计算价格功能

Webpack如何构建Electron应用

以上是Angular图片上传预览路径问题的解决的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn