xiangpei
2025-06-02 1771aa17eb020c4ef22bc8addf83ed2ae97cdfac
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package cn.lili.utils;
 
import cn.lili.common.exception.FileFormatNotSupport;
import cn.lili.modules.lmk.domain.entity.LmkFile;
import cn.lili.modules.lmk.enums.general.FileTypeEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;
 
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
 
/**
 * @author 29443
 * @version 1.0
 * @date 2022/4/25
 */
public class FileUtil {
 
    /**
     * 获取文件后缀
     *
     * @param fileName
     * @return
     */
    public static String getSuffix(String fileName) {
        String suffix = fileName.substring(fileName.lastIndexOf('.') + 1);
        return suffix;
    }
 
    /**
     * 获取该文件上传到oss哪个目录
     *
     * @param suffix 文件后缀
     * @return
     */
    public static String getFileType(String suffix) {
        String fileType = "";
        for (FileTypeEnum type : FileTypeEnum.values()) {
            if (type.getSuffixs().contains(suffix)) {
                fileType = type.getType();
                return fileType;
            }
        }
        if (StringUtils.isBlank(fileType)) {
            throw new FileFormatNotSupport("文件格式" + suffix + "不支持", 500);
        }
        return fileType;
    }
 
    /**
     * 获取文件的信息,调用此方法默认普通上传
     *
     * @param file
     * @return
     */
    public static LmkFile getFileInfo(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String random = generateFileKey();
        String suffix = getSuffix(originalFilename);
        String fileType = getFileType(suffix);
        String fileKey = String.format("%s/%s.%s", fileType, random, suffix);
 
        LmkFile fileInfo = new LmkFile();
        fileInfo.setFileKey(fileKey);
        fileInfo.setOriginalFileName(originalFilename);
        fileInfo.setFileType(file.getContentType());
        fileInfo.setFileSize(file.getSize());
 
        return fileInfo;
    }
 
 
    /**
     * 获取fileKey
     *
     * @return
     */
    public static String generateFileKey() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String no = format.format(new Date());
        Random random = new Random();
        for (int i = 0; i < 5; i++) {
            no += random.nextInt(10);
        }
        return no;
    }
 
}