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 

 

转载于:https://www.cnblogs.com/xiaomaotao/p/10371037.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值