gaoluyang
2026-06-24 c0cb161bb52ce0fbdce5c66ec391d107c75e2452
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import { message } from 'ant-design-vue';
 
enum UploadType {
  Image = 'image',
  Video = 'video',
  Voice = 'voice',
}
 
const useBeforeUpload = (type: UploadType, maxSizeMB: number) => {
  const fn = (file: File): boolean => {
    let allowTypes: string[] = [];
    let name = '';
 
    switch (type) {
      case UploadType.Image: {
        allowTypes = [
          'image/jpeg',
          'image/png',
          'image/gif',
          'image/bmp',
          'image/jpg',
        ];
        maxSizeMB = 2;
        name = '图片';
        break;
      }
      case UploadType.Video: {
        allowTypes = ['video/mp4'];
        maxSizeMB = 10;
        name = '视频';
        break;
      }
      case UploadType.Voice: {
        allowTypes = [
          'audio/mp3',
          'audio/mpeg',
          'audio/wma',
          'audio/wav',
          'audio/amr',
        ];
        maxSizeMB = 2;
        name = '语音';
        break;
      }
    }
    // 格式不正确
    if (!allowTypes.includes(file.type)) {
      message.error(`上传${name}格式不对!`);
      return false;
    }
    // 大小不正确
    if (file.size / 1024 / 1024 > maxSizeMB) {
      message.error(`上传${name}大小不能超过${maxSizeMB}M!`);
      return false;
    }
 
    return true;
  };
 
  return fn;
};
 
export { UploadType, useBeforeUpload };