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,此时就没有问题了~
  • 相关阅读:
    【leetcode】ZigZag——easy
    联合
    AddChildViewController
    imageWithRender(图片的渲染模式)
    13.范型函数的使用:将字典合并到当前字典
    12.代码获取命名空间名称,并创建相应的类(anyClass 应用)
    13.static 面向对象
    11.swift 单例
    swift String 扩展
    swift UIView 扩展
  • 原文地址:https://www.cnblogs.com/liudongpei/p/8033348.html
Copyright © 2011-2022 走看看