vue3 上传头像

<template>
<el-form
    ref="ruleFormRef"
    :model="ruleForm"
    :rules="rules"
    label-width="120px"
    class="demo-ruleForm mt-20px"
    :size="formSize"
    status-icon
    label-position="top"
    :inline="true"
  >
    <el-col :span="24">
      <el-form-item label="证件照片" prop="imageId">
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :http-request="uploadFile"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-col>
  </el-form>
</template>
<script setup lang=ts>
const ruleForm = reactive<any>({
  name: '',
  imageId: '',
  gender: '',
})
// 图片上传
const imageUrl = ref('')

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => { //校验
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('上传图片格式限制为JPG、PNG')
    return false
  } else if (rawFile.size / 1024 / 1024 > 50) {
    ElMessage.error('文件大小不能超过50MB!')
    return false
  }
  return true
}

const uploadFile: any = (param: UploadRequestOptions) => {
  let formData = new FormData()
  formData.append('file', param.file)
  common.uploadImagApi(formData).then((res) => {
    imageUrl.value = res[0].url
    ruleForm.imageId = res[0].id
    ElMessage.success('上传成功')
  })
}
</script>
<style lang="less" scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值