使用element ui 里的upload 上传图片

这是一个关于在Vue中实现头像上传功能的示例。代码通过el-upload组件进行文件上传,限制了上传文件必须为JPG格式且大小不超过2MB。在beforeAvatarUpload方法中进行了格式和大小的验证。当文件上传成功后,使用updateAvatarAPI更新头像,并通过FileReader读取文件内容转换为DataURL显示。
摘要由CSDN通过智能技术生成
<template>
  <div>
    <el-upload
  action="#"
  class="avatar-uploader"
  :show-file-list="false"
  :before-upload="beforeAvatarUpload" 
  :http-request="asd"
  >
  <img v-if="imageUrl" :src="imageUrl" class="avatar">
  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>

  </div>
</template>
<script>
import { updateAvatarAPI } from '@/api/user'
export default {
  data() {
    return {
      imageUrl: ''
    }
  },
  methods: {
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      // console.log(file)
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    asd({ file }) {
      // console.log(file)
      const fd = new FileReader()
      fd.readAsDataURL(file)
      fd.onload = async () => {
        this.imageUrl = fd.result
        await updateAvatarAPI({ avatar: this.imageUrl })
      }
    }
  }
}
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值