在项目我们经常遇到在表单内上传文件必填的场景,在element ui 官网里没有这方面的例子,下面分享一下自己写的代码
<el-dialog v-model="dialogVisible" :title="dialogTitle" width="550" align-center @close="checkClose">
<el-form
:model="checkForm"
:disabled="formDisabled"
:rules="checkfromRules"
ref="checkFormRef"
label-width="100px">
<el-form-item label="文件上传" prop="checkFile">
<!-- accept=".jpg, .png, .jpeg, .pdf , .doc, .docx" -->
<el-upload
style="width: 100%"
v-model:file-list="fileData"
class="upload-demo"
multiple
:limit="1"
:required="true"
:on-remove="handleRemove"
:auto-upload="false"
:before-upload="beforeAvatarUpload"
:on-change="uploadChange">
<el-button>上传文件</el-button>
</el-upload>
</el-form-item>
</el-form>
<template #footer>
<div class="dialog-footer">
<el-button @click="dialogVisible = false">取 消</el-button>
<el-button type="primary" @click="submitForm(checkFormRef)" :loading="submitLoading">确定</el-button>
</div>
</template>
</el-dialog>
声明变量:
const checkForm = ref({
checkFile: '',
})
const checkFormRef = ref()
const checkfromRules = reactive({
checkFile: [{ required: true, validator: uploadFileChange, trigger: 'change' }],
})
const fileData = ref([])
上传校验方法提示:
function uploadFileChange(rule, value, callback) {
if (fileData.value.length === 0) {
return callback('请选择需要上传的文件')
} else {
return true
}
}
上传文件、移除文件方法:
//文件上传
const uploadChange = (uploadFile, uploadFiles) => {
fileData.value = uploadFiles
checkFormRef.value.validateField(['checkFile']) //移除上传文件错误提示!这是重点!!
}
//移除文件
const handleRemove = (uploadFile, uploadFiles) => {
uploadFiles.forEach((item) => {
console.log(item.raw)
})
fileData.value = uploadFiles
}
上传文件添加上传限制条件(请上传JPG/PNG格式、240px*240px以上、1:1、2MB以内的图标):
const beforeAvatarUpload = (file) => {
const isJPG = file.type === 'image/jpg' || file.type === 'image/png' || file.type === 'image/jpeg'
const isLt2M = file.size / 1024 / 1024 < 2
if (!isJPG) {
ElMessage.error('上传图片只能是 JPG、PNG格式!')
}
if (!isLt2M) {
ElMessage.error('上传图片大小不能超过 2MB!')
}
//图片大小
const isSize = new Promise(function (resolve, reject) {
let width = 40
let height = 40
let _URL = window.URL || window.webkitURL
let img = new Image()
img.onload = function () {
let valid = img.width > 40 && img.height > 40 && img.width === img.height
valid ? resolve() : reject()
}
img.src = _URL.createObjectURL(file)
}).then(
() => {
return file
},
() => {
ElMessage.error('上传的图片尺寸必须大于40px*40px且比例为1:1!')
return Promise.reject()
}
)
return isJPG && isLt2M && isSize
}
提交表单方法:
const submitForm = (formEl) => {
formEl.validate((valid, fields) => {
if (valid) {
const formData = new FormData() //需要把上传的文件转为二进制
fileData.value.forEach((item) => {
formData.append('file', item.raw)
})
//下面就是调接口了
submitLoading.value = true
addlist(formData).then((res) => {
if (res.code === 200) {
submitLoading.value = false
dialogVisible.value = false
ElMessage.success('添加成功')
} else {
submitLoading.value = false
ElMessage.error(res.msg)
}
})
} else {
console.log('error submit!', fields)
}
})
}
点击确定的时候:
上传文件后:
完美😍