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 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM