Naive UI Upload上传组件如何自定义上传前文件验证?
在用Naive UI的Upload组件做图片上传时,想在上传前同时验证文件类型和大小,但按照文档写before-upload方法后,虽然能阻止上传却没提示错误信息,这是怎么回事?
我试过这样写代码:before-upload={() => { console.log('检测文件'); return false; }},但点击选择文件后直接没反应。后来改成返回Promise后提示消失了,但错误提示还是不显示:
beforeUpload(file) {
const isJpeg = file.type === 'image/jpeg';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJpeg) {
ElMessage.error('只能上传JPG格式');
return false;
}
if (!isLt2M) {
ElMessage.error('图片大小不能超过2MB');
return false;
}
return new Promise((resolve) => setTimeout(resolve, 1000)); // 模拟延迟
},
现在虽然能正确阻止上传,但错误提示只在控制台有一瞬间闪现,页面上完全看不到错误信息,用户完全不知道哪里错了…
改成这样:
import { useMessage } from 'naive-ui';
const message = useMessage();
beforeUpload(file) {
const isJpeg = file.type === 'image/jpeg';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJpeg) {
message.error('只能上传JPG格式');
return false;
}
if (!isLt2M) {
message.error('图片大小不能超过2MB');
return false;
}
return true;
}