解决el-upload组件文件校验不通过时预览文件仍然显示的问题
场景
我的文件要与表单一起,点击保存按钮时才进行上传提交。
文件要求:
- 仅支持word/excel/jpg/png/rar格式;
- 单个文件不超过100M;
- 最多可以添加10个文件。
原始代码:
<el-upload v-model:file-list="form.addFiles" class="upload"
:on-change="handleOnUploadChange" :auto-upload="false"
:before-remove="handleBeforeRemove" :limit="10" :on-exceed="handleExceed">
<template #tip>
<div class="el-upload__tip">
支持word/excel/jpg/png/rar类型文件,单个文件不超过100M。
</div>
</template>
<el-button class="btn-add-affix" type="primary">
添加附件
</el-button>
</el-upload>
const allowedTypes = ['application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'image/jpeg', 'image/png', 'application/x-rar-compressed'];
function handleOnUploadChange(uploadFile: any) {
console.log("onUploadChange", uploadFile);
if (!allowedTypes.includes(uploadFile.raw.type)) {
ElMessage.error('文件格式不支持,请重新上传!')
return
}
if (uploadFile.size / 1024 / 1024 > 100) {
ElMessage.error('单个文件大小不能超过100MB!')
return
}
}
此时我发现加上这段代码之后,即使上传pdf类型的文件(不通过格式类型),在预览区域仍然可以显示该文件。
解决:
由于auto-upload = false,在beforeUpload钩子函数里不会触发,与on-Change钩子函数冲突。
最终校验逻辑加在on-change方法里。
只需要在文件校验不通过时从列表中删除该文件即可删除预览区域的显示。具体逻辑如下:
function handleOnUploadChange(uploadFile: any) {
console.log("onUploadChange", uploadFile);
if (!allowedTypes.includes(uploadFile.raw.type)) {
ElMessage.error('文件格式不支持,请重新上传!')
handleRemove(uploadFile, form.value.addFiles)
return
}
if (uploadFile.size / 1024 / 1024 > 100) {
ElMessage.error('单个文件大小不能超过100MB!')
handleRemove(uploadFile, form.value.addFiles)
return
}
}
/**
* 从addFiles列表中删除不合规的文件
* @param file: 指当前添加的附件
* addFileList: 指表单数据addFiles
*/
function handleRemove(file:any, addFileList:any) {
let index = -1;
addFileList.forEach((e:any, i:any) => {
if (e.uid == file.uid) {
index = i;
}
});
if(index >= 0){
addFileList.splice(index, 1);
}
}