vue3+ts二次封装el-upload实现上传图片校验

说明

项目开发中,常常需要对上传图片做大小、类型、宽高校验

实现要点

  • el-upload中定义:before-upload="handleBeforeUpload"事件
  • img.onload为异步事件,需要Promise包裹才能真正实现校验,直接return true|false是没用的

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<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); //自定义接口上传
}

 

posted @   南无、  阅读(443)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示