<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>
vue3 上传头像
最新推荐文章于 2024-09-03 09:34:08 发布