用户选择头像后, 要在前端做预览的实现方式

  1. 展示的上传按钮
    <!-- 图片,用来展示用户选择的头像 -->
    <img class="the_img" src="../../../assets/images/avatar.jpg" v-if="!this.avatar"/>
    <img class="the_img" alt="" :src="this.avatar" v-else />
    <div class="btn-box">
      <input type="file" accept="image/*" style="display: none" @change="onFileChange" ref="iptRef"/>
   
      <el-button size="small" type="primary" icon="el-icon-plus" @click="picBtn">点击上传</el-button >
       </div>
  </div> 
  1. 具体实现的代码
// 点击上传图片
    picBtn() {
      this.$refs.iptRef.click()
    },
    // 上传图片事件
    onFileChange(e) {
      const files = e.target.files
      // 没有选中文件
      if (files.length === 0) {
        this.avatar = ''
        this.$message.warning('请选择你要上传的头像')
      } else {
        /**
         * 方式1: 使用FileReader来读取选择的前端文件, 转换为base64字符串, 给img标签渲染
         *
         // 创建文件读取对象
        const fileDoc = new FileReader()
        // 调用readAsDataURL函数,读取文件
        fileDoc.readAsDataURL(files[0])
        // 监听fileDoc的onload事件
        fileDoc.onload = (e) => {
         // 通过e.target.result获取到 读到的内容,值是base64格式的字符串
         this.avatar = e.target.result
        }
         */

        /**
         * 方式2
         // 使用URL.createObjURL()来转换文件变成图片地址(纯前端本地)
        this.avatar = URL.createObjectURL(files[0])
         */
      }
    }
posted @ 2023-01-26 00:38  NaziriteGTC  阅读(79)  评论(0)    收藏  举报