zoukankan      html  css  js  c++  java
  • 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,此时就没有问题了~
  • 相关阅读:
    三毛
    深复制和浅复制
    并发和并行
    PhotoKit保存图片到相册
    利用代码块
    Maven打包程序
    通过Nginx+Tomcat简单实现发布时不间断服务的提供
    C# java MD5加密方不一致问题
    SpringBoot读取配置值的方式
    Java8之集合排序
  • 原文地址:https://www.cnblogs.com/liudongpei/p/8033348.html
Copyright © 2011-2022 走看看