zoukankan      html  css  js  c++  java
  • vue 结合 FileReader() 实现上传图片预览功能

    项目中 身份证上传需求:

    <div class="ID_pic_wrap">
                <ul>
                    <li>
                        <img src="../../assets/images/id_face_pic@2x.png" >
                        <span class="cancel_btn" @click="delFun()"></span>
                        <input id="id_face_file" @change="uploadFile1" ref="files1" type="file">
                        <img id="showIdFaceSrc" :src="src1" alt="">
                    </li>
                    <li>
                        <img src="../../assets/images/id_behand_pic@2x.png" >
                        <span class="cancel_btn" @click="delFun()"></span>
                        <input id="id_behand_file" @change="uploadFile2"   ref="files2" type="file">
                        <img id="showIdbehandSrc" :src="src2" alt="">
                    </li>
                </ul>
            </div>
    

      

    uploadFile1(e){
                let _this = this;
                // console.log(e.target.files[0])
                if (!e || !window.FileReader) return  // 看支持不支持FileReader
                let reader = new FileReader()
                reader.readAsDataURL(e.target.files[0]) // 这里是最关键的一步,转换就在这里 (参数必须是blob对象)
                reader.onloadend = function () {
                    _this.src1 = this.result
                }
            },
            uploadFile2(e){
    
                console.log(222)
                let _this = this;
                if (!e || !window.FileReader) return  // 看支持不支持FileReader 
                // console.log(e.target.files[0]);
                let reader = new FileReader()
                reader.readAsDataURL(e.target.files[0]) // 这里是最关键的一步,转换就在这里(参数必须是blob对象)
           reader.onloadend = function () { 
            _this.src2 = this.result 
           } 
          }, 
          delFun(){ 
            if(this.src1){ 
              this.src1 = ""; 
              this.$refs.files1.value=""; //这里清空input的value 不然不可以选择相同的文件 
            }else if(this.src2){ 
            this.src2 = ""; 
            this.$refs.files2.value=""; //这里清空input的value 不然不可以选择相同的文件
          }
       },

      note:

         FileReader() 兼容性

    更多信息 移步:https://developer.mozilla.org/zh-CN/docs/Web/API/FileReader 

  • 相关阅读:
    12-五子棋游戏:享元模式
    11-制作糖醋排骨:外观模式
    10-蒸馒头:装饰者模式
    09-公司层级结构:组合模式
    08-开关与电灯:桥接模式
    07-电源转换:适配器模式
    将博客搬至CSDN
    iview和element中日期选择器快捷选项的定制控件
    详解AJAX工作原理以及实例讲解(通俗易懂)
    最全肌肉锻炼动图
  • 原文地址:https://www.cnblogs.com/xiaomaotao/p/10371037.html
Copyright © 2011-2022 走看看