vue3+ts二次封装el-upload实现上传图片校验
说明
项目开发中,常常需要对上传图片做大小、类型、宽高校验
实现要点
- el-upload中定义:before-upload="handleBeforeUpload"事件
- img.onload为异步事件,需要Promise包裹才能真正实现校验,直接return true|false是没用的
代码
<el-upload :before-update="handleBeforeUpdate" :http-request="uploadFile">
// 自定义上传组件样式
</el-upload>
// 上传前的文件校验
function handleBeforeUpload(file: UploadRawFile) {
const inType = /.(jpg|jpeg|png|JPG|PNG|JPEG)$/gi.test(file.name);
if (!inType) {
ElMessage.warning("上传图片格式应为:PNG、JPG、JPEG");
return false;
}
const inLimit = file.size / 1024 / 1024 < 10;
if (!inLimit) {
ElMessage.warning("上传图片不能大于10MB");
return false;
}
const inSize = new Promise<void>(function (resolve, reject) {
// 因为onload是异步事件,所以需要封装在promise中
var img_src = URL.createObjectURL(file);
var img_temp = new Image();
img_temp.src = img_src;
img_temp.onload = function () {
img_temp.width === img_temp.height ? resolve() : reject();
};
}).then(
() => {
return file;
},
() => {
ElMessage.warning("上传图片宽高比应为1:1");
return Promise.reject();
}
);
return inType && inLimit && inSize;
}
// 自定义上传事件
async function uploadFile(options: UploadRequestOptions): Promise<any> {
const { data: fileInfo } = await uploadFileApi(options.file); //自定义接口上传
}

浙公网安备 33010602011771号