zss
2025-02-17 087991c76f078defe5eb55d84223021b4199fb3d
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
package com.yuanchu.mom.utils;
 
import com.yuanchu.mom.exception.MyFileException;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.FileSystemUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;
 
import javax.annotation.PostConstruct;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
 
/**
 * 保存文件工具
 */
@Slf4j
@Component
public class FileSaveUtil {
 
    // 取yml中的路径 + /
    private static String FILE_PATH;
 
    private static String WORD_URL_PATH;
 
    private static String[] ALLOWED;
 
    @Value("${file.path}")
    private String file;
 
    @Value("${wordUrl}")
    private String wordUrl;
 
    @Value("${file.allowed}")
    private String[] allowed;
 
    @PostConstruct
    public void getFile() {
        FILE_PATH = this.file;
    }
 
    @PostConstruct
    public void getWordUrl(){
        WORD_URL_PATH = this.wordUrl;
    }
 
    @PostConstruct
    public void getAllowed(){
        ALLOWED = this.allowed;
    }
    /**
     * 存储文件主函数
     * @param file 文件二进制流
     * @return 返回文件名称用于存储数据库
     */
    public static String StoreFile(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        // 生成随机名称:时间_随机6位数字
        String FileName = System.currentTimeMillis() + "_" + MyUtil.getNumber(6);
        String suffix = null;
        if (originalFilename != null) {
            suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            // 如果后缀名不通过抛出异常
            if (!isFileAllowed(suffix)){
                throw  new MyFileException(suffix);
            }
        }
        // 名称拼接
        String fileName = FileName + suffix;
        // 进行存储
        try {
            storeFileWithFileName(file.getBytes(), fileName);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return fileName;
    }
 
    public static Boolean DeleteFile(String fileName) {
        if (ObjectUtils.isEmpty(fileName)) {
            return false;
        }
        return FileSystemUtils.deleteRecursively(new File(FILE_PATH + "/" + fileName));
    }
    /**
     * 存储文件函数
     * @param content 文件二进制流
     * @param fileName 文件名称
     */
    private static void storeFileWithFileName(byte[] content, String fileName) {
        // 存储路径
        String path = FILE_PATH + File.separatorChar;
        // 目录不存在则创建
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        // 开始存储
        try (FileOutputStream os = new FileOutputStream(path + fileName);
             ByteArrayInputStream is = new ByteArrayInputStream(content)) {
             IOUtils.copy(is, os);
        } catch (IOException e) {
            MyUtil.PrintLog("存储文件异常:" + e);
        }
    }
 
    /**
     * 判断文件是否被允许上传
     *
     * @param fileName 文件名
     * @return 允许true, 否则false
     */
    private static boolean isFileAllowed(String fileName) {
        // 获取后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        for (String allow : ALLOWED) {
            if (allow.equals(suffixName)) {
                return true;
            }
        }
        return false;
    }
 
 
    /**
     * 保存文件到word文件夹里
     * @param file
     * @return
     */
    public static String uploadWordFile(MultipartFile file) {
        String urlString;
        String pathName;
        String path;
        try {
            String contentType = file.getContentType();
            if (contentType != null && contentType.startsWith("image/")) {
                // 是图片
                path = FILE_PATH;
            } else {
                // 是文件
                path = WORD_URL_PATH;
            }
            File realpath = new File(path);
            if (!realpath.exists()) {
                realpath.mkdirs();
            }
            pathName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMMddHHmmss")) + "-" + file.getOriginalFilename();
            urlString = realpath + "/" + pathName;
            file.transferTo(new File(urlString));
            return pathName;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}