当需要头像上传得时候.图片按照格式修改为base64

<template>
   <el-card class="userAvatar-container">
     <!-- 面板屑导航 -->
 <Bread name='个人中心' first='更换头像'></Bread>
    <!-- 用来展示头像的盒子 -->
    <div class="avatar-box">
      <img :src="userImg || ImgDefault" alt="" />
    <div class="btns">
    <!-- 文件选择框 -->
    <input type="file" accept="image/*" style="display: none;" ref="fileRef" @change="onFileChange" />
    <el-button type="primary" icon="el-icon-plus" @click="xuanze">选择图片</el-button>
    <el-button type="success" icon="el-icon-upload" :disabled="isDisabled" @click="shangchuan">上传头像</el-button>
</div>
    </div>
  </el-card>
</template>

<script>
// 导入默认图片
import ImgDefault from '../../assets/images/avatar.jpg'
import { mapState, mapActions } from 'vuex'
import { reqUpdateAvatar } from '../../api/changeav.js'
export default {
  name: 'UserAvatar',
  data () {
    return {
      isDisabled: true,
      // 头像的图片
      userImg: '',
      ImgDefault
    }
  },
  computed: {
    ...mapState('user', ['userinfo'])
  },
  created () {
    this.AgetUserFrom()
    this.userImg = this.userinfo.user_pic
  },
  methods: {
    ...mapActions('user', ['AgetUserFrom']),
    async shangchuan () {
      const res = await reqUpdateAvatar(this.userImg)
      console.log(res)
      if (res.data.code !== 0) return this.$message.error(res.data.message)
      this.$message.success(res.data.message)
      // 3. 重新获取个人信息
      // 4. 禁用按钮
      this.isDisabled = true
      this.AgetUserFrom()
    },
    xuanze () {
      this.$refs.fileRef.click()
    },
    // 文件选择框发生了 change 变化
    onFileChange (e) {
      console.log(e, 999)
      const file = e.target.files[0]
      // 1. 判断是否选择了图像
      if (!file) {
        // 如果用户没选 将默认头像显示和按钮禁用
        this.isDisabled = true
        this.userImg = ImgDefault
        return this.$message.warning('请选择上传的图像')
      }
      // 2. 限制上传文件的大小 1.5M
      if (file.size / 1024 / 1024 > 1.5) return this.$message.warning('图像大小不能超过1.5M')
      // 3. 处理base64格式图片 回显
      //  3.1 使用fileReader文件读取对象 处理base64格式
      const fileReader = new FileReader()
      console.log(fileReader, 888)
      // 3.2 使用fileReader实例读取文件地址readAsDataURL()
      fileReader.readAsDataURL(file)
      // 3.3在上传成功后load事件中,获取文件的base64格式的地址
      fileReader.addEventListener('load', () => {
        console.log(fileReader.result) // base64格式的图片
        this.userImg = fileReader.result
        // 3.4 启用禁用上传的按钮
        this.isDisabled = false
      })
    }
  }
}
</script>

<style lang="less" scoped>
.userAvatar-container {
  padding: 0 0 20px 20px;

  .avatar-box {
    img {
      width: 350px;
      height: 350px;
      object-fit: cover;
    }
  }

  .btns {
    padding-top: 10px;
  }
}
</style>

Supongo que te gusta

Origin blog.csdn.net/wangyangzxc123/article/details/121257739
Recomendado
Clasificación