1
yangbin
2024-08-15 fc38e2635216775a80210d0df109dc6174d66813
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
package org.jeecg.modules.utils.file;
 
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.FileUploadResult;
import org.jeecg.common.util.SHA256Util;
import org.jeecg.modules.utils.DateUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;
 
@Slf4j
@Component
public class FileUtils {
 
    private static String fileUploadFolder;
 
    @Value("${jeecg.path.upload}")
    public void setFileUploadFolder(String fileUploadFolder) {
        FileUtils.fileUploadFolder = fileUploadFolder;
    }
 
    /**
     * 文件路径上传保存
     * @param filePath
     * @return
     */
    public static FileUploadResult uploadFilePath(String filePath) {
        File file = new File(filePath);
        if(file == null) {
            return null;
        }
        String fileName = file.getName();
        String suffix = getFileSuffix(fileName);
        Date currentDate = DateUtil.getNow();
        String monthStr = DateUtil.format(currentDate, DateUtil.STR_YEAR_MONTH);
        //相对路径
        String relativePath = "/" + monthStr + "/" + DateUtil.getDayStr(currentDate) + "/";
        //绝对路径
        String absolutePath =  fileUploadFolder + "/" + monthStr + "/" + DateUtil.getDayStr(currentDate) + "/";
        String fileNameNonSuffix = getFilenameNonSuffix(fileName);
        if(fileNameNonSuffix == null)
            return null;
        String encodeFileName = SHA256Util.getSHA256Str(fileNameNonSuffix + System.currentTimeMillis());
        if(StringUtils.isNotBlank(suffix)) {
            encodeFileName = encodeFileName + "." + suffix;
        }
        Long b = uploadFileInput(file, absolutePath, encodeFileName);
        FileUploadResult dto = new FileUploadResult();
        dto.setFileName(fileNameNonSuffix);
        dto.setFilePath(encodeFileName);
        dto.setFilePath(relativePath);
        dto.setFileSize(b);
        dto.setFileSuffix(suffix);
        return dto;
    }
 
    /**
     * 文件File上传保存
     * @param file
     * @return
     */
    public static FileUploadResult uploadFileInFile(File file) {
        if(file == null) {
            return null;
        }
        String fileName = file.getName();
        String suffix = getFileSuffix(fileName);
        Date currentDate = DateUtil.getNow();
        String monthStr = DateUtil.format(currentDate, DateUtil.STR_YEAR_MONTH);
        //相对路径
        String relativePath = "/" + monthStr + "/" + DateUtil.getDayStr(currentDate) + "/";
        //绝对路径
        String absolutePath =  fileUploadFolder + "/" + monthStr + "/" + DateUtil.getDayStr(currentDate) + "/";
        String fileNameNonSuffix = getFilenameNonSuffix(fileName);
        if(fileNameNonSuffix == null) {
            return null;
        }
        String encodeFileName = SHA256Util.getSHA256Str(fileNameNonSuffix + System.currentTimeMillis());
        if(StringUtils.isNotBlank(suffix)) {
            encodeFileName = encodeFileName + "." + suffix;
        }
        Long b = uploadFileInput(file, absolutePath, encodeFileName);
        FileUploadResult dto = new FileUploadResult();
        dto.setFileName(fileNameNonSuffix);
        dto.setFileEncodeName(encodeFileName);
        dto.setFilePath(relativePath);
        dto.setFileSize(b);
        dto.setFileSuffix(suffix);
        return dto;
    }
 
 
    /**
     * MultipartFile 方式保存
     * @param file
     * @return
     */
    public static FileUploadResult uploadMultipartFile(MultipartFile file) {
        if(file == null || file.isEmpty()) {
            return null;
        }
        String fileName = file.getOriginalFilename();
        String suffix = getFileSuffix(fileName);
        Date currentDate = DateUtil.getNow();
        String monthStr = DateUtil.format(currentDate, DateUtil.STR_YEAR_MONTH);
        //相对路径
        String relativePath = "/" + monthStr + "/" + DateUtil.getDayStr(currentDate) + "/";
        //绝对路径
        String absolutePath =  fileUploadFolder + "/" + monthStr + "/" + DateUtil.getDayStr(currentDate) + "/";
        String fileNameNonSuffix = getFilenameNonSuffix(fileName);
        if(fileNameNonSuffix == null)
            return null;
        String encodeFileName = SHA256Util.getSHA256Str(fileNameNonSuffix + System.currentTimeMillis());
        Long fileSize = file.getSize();
        if(StringUtils.isNotBlank(suffix)) {
            encodeFileName = encodeFileName + "." + suffix;
        }
        boolean b = uploadFile(file, absolutePath, encodeFileName);
        if(!b)
            return null;
        FileUploadResult dto = new FileUploadResult();
        dto.setFileName(fileNameNonSuffix);
        dto.setFilePath(encodeFileName);
        dto.setFilePath(relativePath);
        dto.setFileSize(fileSize);
        dto.setFileSuffix(suffix);
        return dto;
    }
 
    public static void downLoadFile(HttpServletResponse response, String fileName, String filePath, String toFileName) {
        String absolutePath = fileUploadFolder + filePath;
        File file = new File(absolutePath , fileName);
        if(file.exists()) {
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                response.setHeader("Content-Type", "application/octet-stream;charset=utf-8"); // 告诉浏览器输出内容为流
                response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(toFileName, "UTF-8"));
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            }catch (Exception e) {
                log.error(e.getMessage(), e.getStackTrace());
            }finally {
                if(bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                    }
                }
                if(fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                    }
                }
            }
        }else {
 
        }
    }
 
 
 
    /**
     * 上传文件工具类
     * @param file
     * @param path
     * @param fileNewName  新的文件名
     * @return
     */
    public static Long uploadFileInput(File file, String path, String fileNewName) {
        File targetFile = new File(path, fileNewName);
        if(!targetFile.getParentFile().exists()){
            targetFile.getParentFile().mkdirs();
        }
        try {
            FileInputStream fis = new FileInputStream(file);
            FileOutputStream fos = new FileOutputStream(targetFile);
            //FileInputStream fis = new FileInputStream(file);
            byte[] bytes = new byte[1024 * 4];
            int index = 0;
            long total = 0;
            while ((index = fis.read(bytes)) != -1) {
                fos.write(bytes, 0, index);
                total =+ index;
            }
            fis.close();
            fos.flush();
            fos.close();
            return total;
        } catch (Exception e) {
            log.error(e.getMessage(), e.getStackTrace());
            return 0L;
        }
    }
    /**
     * 上传文件工具类
     * @param multipartFile
     * @param path
     * @param fileNewName  新的文件名
     * @return
     */
    public static boolean uploadFile(MultipartFile multipartFile, String path, String fileNewName) {
        File targetFile = new File(path, fileNewName);
        if(!targetFile.getParentFile().exists()){
            targetFile.getParentFile().mkdirs();
        }
        try {
            multipartFile.transferTo(targetFile);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage(), e.getStackTrace());
            return false;
        }
    }
 
    /**
     * 获取文件后缀  无后缀文件返回NULL
     * @param fileName
     * @return
     */
    public static String getFileSuffix(String fileName) {
        if (fileName.contains(".")) {
            String suffix = fileName.substring(fileName.lastIndexOf('.') + 1);
            return suffix;
        }else {
            return null;
        }
 
    }
 
    /**
     * 获取文件名 不带后缀和点号
     * @param fileName
     * @return
     */
    public static String getFilenameNonSuffix(String fileName) {
        if (fileName.contains(".")) {
            String filename = fileName.substring(0, fileName.lastIndexOf('.'));
            return filename;
        }else {
            return fileName;
        }
 
    }
 
 
 
    public static String checkFileEncode(File file) {
        String charset = "GBK";
        byte[] first3Bytes = new byte[3];
        BufferedInputStream bis = null;
        try {
            boolean checked = false;
            bis = new BufferedInputStream(new FileInputStream(file));
            bis.mark(0);
            int read = bis.read(first3Bytes, 0, 3);
            if (read == -1)
                return charset;
            if(first3Bytes[0] == (byte) 0xFF && first3Bytes[1] == (byte) 0xFE ) {
                charset = "UTF-16LE";
                checked = true;
            }else if ( first3Bytes[0] == (byte) 0xFE && first3Bytes[1] == (byte) 0xFF ) {
                charset = "UTF-16BE";
                checked = true;
            }else if (first3Bytes[0] == (byte) 0xEF && first3Bytes[1] == (byte) 0xBB && first3Bytes[2] == (byte) 0xBF ) {
                charset = "UTF-8";
                checked = true;
            }
            bis.reset();
            if (!checked) {
                while ((read = bis.read()) != -1 ) {
                    if ( read >= 0xF0 )
                        break;
                    if ( 0x80 <= read && read <= 0xBF ) // 单独出现BF以下的,也算是GBK
                        break;
                    if ( 0xC0 <= read && read <= 0xDF ) {
                        read = bis.read();
                        if ( 0x80 <= read && read <= 0xBF ) // 双字节 (0xC0 - 0xDF) (0x80 - 0xBF),也可能在GBK编码内  
                             continue;
                        else
                            break;
                    } else if ( 0xE0 <= read && read <= 0xEF ) {
                        // 也有可能出错,但是几率较小
                        read = bis.read();
                        if ( 0x80 <= read && read <= 0xBF ) {
                            read = bis.read();
                            if ( 0x80 <= read && read <= 0xBF ) {
                                 charset = "UTF-8";
                                 break;
                            } else
                                break;
                        } else {
                            break;
                        }
                    }
                }
            }
            return charset;
        }catch (Exception e) {
            return null;
        }finally {
            if(bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                }
            }
        }
 
    }
 
 
}