vue前端上傳圖片並回顯,同時獲取文件的base64編碼


 

<el-form-item label="部位縮略圖:" required>
                    <div class="upload-img" style="width: 148px; height: 100px;" >
                        <input type="file" ref="fileBtn" @change="uploadImg" />
                        <img v-if="imgSrc" :src="imgSrc" class="img" ref="img" style="width: 100px;height: 100px" />
                    </div>
                </el-form-item>
data() {
      return {
        imgInfo: null,
        imgSrc: null
      };
    },
methods: {
  uploadImg() {
        const that = this
        const inputFile = this.$refs.fileBtn.files[0]
        let res = ''
        this.inputFile = inputFile
        if (this.inputFile) {
          let inputFile = this.inputFile
          if (inputFile.type !== 'image/jpeg' && inputFile.type !== 'image/png' && inputFile.type !== 'image/gif') {
            net.message(this, "不是有效的圖片文件!", "warning");
            return
          }
          if (inputFile.size > 1024*20) {
            net.message(this, "請上傳小於 12KB 的圖片 !", "warning");
            return
          }
          this.imgInfo = Object.assign({}, this.imgInfo, {
            name: inputFile.name,
            size: inputFile.size,
            lastModifiedDate: inputFile.lastModifiedDate.toLocaleString()
          })
          const reader = new FileReader()
          res = reader.readAsDataURL(this.inputFile)
          reader.onloadend = function() {
            const strBase64 = reader.result.substring(0);
            // that.strBase64 = strBase64
          }
          reader.onload = function(e) {
            // console.log(e);
            that.imgSrc = this.result
          }
        } else {
          return
        }
      },  
}

 


免責聲明!

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



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