DESKTOP-LMJ82IJ\Eno
2025-04-07 de2365da21526a6af8e0c1504ed489dcc3617de9
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
package com.vincent.rsf.server.common.utils;
 
import com.vincent.rsf.common.utils.Utils;
import com.vincent.rsf.framework.common.Cools;
import org.apache.tika.Tika;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
 
/**
 * 文件上传下载工具类
 *
 * @author vincent
 * @since 2018-12-14 08:38:53
 */
public class FileServerUtil {
    // 除 text/* 外也需要设置输出编码的 content-type
    private final static List<String> SET_CHARSET_CONTENT_TYPES = Arrays.asList(
            "application/json",
            "application/javascript"
    );
 
    /**
     * 上传文件
     *
     * @param file      MultipartFile
     * @param directory 文件保存的目录
     * @param uuidName  是否用uuid命名
     * @return File
     */
    public static File upload(MultipartFile file, String directory, boolean uuidName)
            throws IOException, IllegalStateException {
        File outFile = getUploadFile(file.getOriginalFilename(), directory, uuidName);
        if (!outFile.getParentFile().exists()) {
            if (!outFile.getParentFile().mkdirs()) {
                throw new RuntimeException("make directory fail");
            }
        }
        file.transferTo(outFile);
        return outFile;
    }
 
    /**
     * 上传base64格式文件
     *
     * @param base64    base64编码字符
     * @param fileName  文件名称, 为空使用uuid命名
     * @param directory 文件保存的目录
     * @return File
     */
    public static File upload(String base64, String fileName, String directory)
            throws FileNotFoundException {
        if (Cools.isEmpty(base64) || !base64.startsWith("data:image/") || !base64.contains(";base64,")) {
            throw new RuntimeException("base64 data error");
        }
        String suffix = "." + base64.substring(11, base64.indexOf(";"));  // 获取文件后缀
        boolean uuidName = Cools.isEmpty(fileName);
        File outFile = getUploadFile(uuidName ? suffix : fileName, directory, uuidName);
        byte[] bytes = Base64.getDecoder().decode(base64.substring(base64.indexOf(";") + 8).getBytes());
 
        FileOutputStream out = new FileOutputStream(outFile);
        try {
            out.write(bytes);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return outFile;
    }
 
    /**
     * 获取上传文件位置
     *
     * @param name      文件名称
     * @param directory 上传目录
     * @param uuidName  是否使用uuid命名
     * @return File
     */
    public static File getUploadFile(String name, String directory, boolean uuidName) {
        // 当前日期作为上传子目录
        String dir = new SimpleDateFormat("yyyyMMdd/").format(new Date());
        // 获取文件后缀
        String suffix = (name == null || !name.contains(".")) ? "" : name.substring(name.lastIndexOf("."));
        // 使用uuid命名
        if (uuidName || name == null) {
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            return new File(directory, dir + uuid + suffix);
        }
        // 使用原名称, 存在相同则加(1)
        File file = new File(directory, dir + name);
        String prefix = Utils.removeSuffix(name, suffix);
        int sameSize = 2;
        while (file.exists()) {
            file = new File(directory, dir + prefix + "(" + sameSize + ")" + suffix);
            sameSize++;
        }
        return file;
    }
 
    /**
     * 查看文件, 支持断点续传
     *
     * @param file       文件
     * @param pdfDir     office转pdf输出目录
     * @param officeHome openOffice安装目录
     * @param response   HttpServletResponse
     * @param request    HttpServletRequest
     */
    public static void preview(File file, String pdfDir, String officeHome,
                               HttpServletResponse response, HttpServletRequest request) {
        preview(file, false, null, pdfDir, officeHome, response, request);
    }
 
    /**
     * 查看文件, 支持断点续传
     *
     * @param file          文件
     * @param forceDownload 是否强制下载
     * @param fileName      强制下载的文件名称
     * @param pdfDir        office转pdf输出目录
     * @param officeHome    openOffice安装目录
     * @param response      HttpServletResponse
     * @param request       HttpServletRequest
     */
    public static void preview(File file, boolean forceDownload, String fileName, String pdfDir, String officeHome,
                               HttpServletResponse response, HttpServletRequest request) {
        CommonUtil.addCrossHeaders(response);
        if (file == null || !file.exists()) {
            outNotFund(response);
            return;
        }
        if (forceDownload) {
            setDownloadHeader(response, Cools.isEmpty(fileName) ? file.getName() : fileName);
        } else {
            // office转pdf预览
            if (OpenOfficeUtil.canConverter(file.getName())) {
                File pdfFile = OpenOfficeUtil.converterToPDF(file.getAbsolutePath(), pdfDir, officeHome);
                if (pdfFile != null) {
                    file = pdfFile;
                }
            }
            // 获取文件类型
            String contentType = getContentType(file);
            if (contentType != null) {
                response.setContentType(contentType);
                // 设置编码
                if (contentType.startsWith("text/") || SET_CHARSET_CONTENT_TYPES.contains(contentType)) {
                    try {
                        String charset = JChardetFacadeUtil.detectCodepage(file.toURI().toURL());
                        if (charset != null) {
                            response.setCharacterEncoding(charset);
                        }
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    }
                }
            } else {
                setDownloadHeader(response, file.getName());
            }
        }
        response.setHeader("Cache-Control", "public");
        output(file, response, request);
    }
 
    /**
     * 查看缩略图
     *
     * @param file      原文件
     * @param thumbnail 缩略图文件
     * @param size      缩略图文件的最大值(kb)
     * @param response  HttpServletResponse
     * @param request   HttpServletRequest
     */
    public static void previewThumbnail(File file, File thumbnail, Integer size,
                                        HttpServletResponse response, HttpServletRequest request) {
        // 如果是图片并且缩略图不存在则生成
//        if (!thumbnail.exists() && isImage(file)) {
//            long fileSize = file.length();
//            if ((fileSize / 1024) > size) {
//                try {
//                    if (thumbnail.getParentFile().mkdirs()) {
//                        ImgUtil.scale(file, thumbnail, size / (fileSize / 1024f));
//                        if (thumbnail.exists() && thumbnail.length() > file.length()) {
//                            FileUtil.copy(file, thumbnail, true);
//                        }
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            } else {
//                preview(file, null, null, response, request);
//                return;
//            }
//        }
//        preview(thumbnail.exists() ? thumbnail : file, null, null, response, request);
 
        preview(file, null, null, response, request);
    }
 
    /**
     * 输出文件流, 支持断点续传
     *
     * @param file     文件
     * @param response HttpServletResponse
     * @param request  HttpServletRequest
     */
    public static void output(File file, HttpServletResponse response, HttpServletRequest request) {
        long length = file.length();  // 文件总大小
        long start = 0, to = length - 1;  // 开始读取位置, 结束读取位置
        long lastModified = file.lastModified();  // 文件修改时间
        response.setHeader("Accept-Ranges", "bytes");
        response.setHeader("ETag", "\"" + length + "-" + lastModified + "\"");
        response.setHeader("Last-Modified", new Date(lastModified).toString());
        String range = request.getHeader("Range");
        if (range != null) {
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
            String[] ranges = range.replace("bytes=", "").split("-");
            start = Long.parseLong(ranges[0].trim());
            if (ranges.length > 1) {
                to = Long.parseLong(ranges[1].trim());
            }
            response.setHeader("Content-Range", "bytes " + start + "-" + to + "/" + length);
        }
        response.setHeader("Content-Length", String.valueOf(to - start + 1));
        try {
            output(file, response.getOutputStream(), 2048, start, to);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 输出文件流
     *
     * @param file 文件
     * @param os   输出流
     */
    public static void output(File file, OutputStream os) {
        output(file, os, null);
    }
 
    /**
     * 输出文件流
     *
     * @param file 文件
     * @param os   输出流
     * @param size 读取缓冲区大小
     */
    public static void output(File file, OutputStream os, Integer size) {
        output(file, os, size, null, null);
    }
 
    /**
     * 输出文件流, 支持分片
     *
     * @param file  文件
     * @param os    输出流
     * @param size  读取缓冲区大小
     * @param start 开始位置
     * @param to    结束位置
     */
    public static void output(File file, OutputStream os, Integer size, Long start, Long to) {
        BufferedInputStream is = null;
        try {
            is = new BufferedInputStream(new FileInputStream(file));
            if (start != null) {
                long skip = is.skip(start);
                if (skip < start) {
                    System.out.println("ERROR: skip fail[ skipped=" + skip + ", start= " + start + " ]");
                }
                to = to - start + 1;
            }
            byte[] bytes = new byte[size == null ? 2048 : size];
            int len;
            if (to == null) {
                while ((len = is.read(bytes)) != -1) {
                    os.write(bytes, 0, len);
                }
            } else {
                while (to > 0 && (len = is.read(bytes)) != -1) {
                    os.write(bytes, 0, to < len ? (int) ((long) to) : len);
                    to -= len;
                }
            }
            os.flush();
        } catch (IOException ignored) {
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException ignored) {
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    System.out.println(e.getMessage());
                }
            }
        }
    }
 
    /**
     * 获取文件类型
     *
     * @param file 文件
     * @return String
     */
    public static String getContentType(File file) {
        String contentType = null;
        if (file.exists()) {
            try {
                contentType = new Tika().detect(file);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return contentType;
    }
 
    /**
     * 判断文件是否是图片类型
     *
     * @param file 文件
     * @return boolean
     */
    public static boolean isImage(File file) {
        return isImage(getContentType(file));
    }
 
    /**
     * 判断文件是否是图片类型
     *
     * @param contentType 文件类型
     * @return boolean
     */
    public static boolean isImage(String contentType) {
        return contentType != null && contentType.startsWith("image/");
    }
 
    /**
     * 设置下载文件的header
     *
     * @param response HttpServletResponse
     * @param fileName 文件名称
     */
    public static void setDownloadHeader(HttpServletResponse response, String fileName) {
        response.setContentType("application/force-download");
        try {
            fileName = URLEncoder.encode(fileName, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
    }
 
    /**
     * 输出404错误页面
     *
     * @param response HttpServletResponse
     */
    public static void outNotFund(HttpServletResponse response) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        outMessage("404 Not Found", null, response);
    }
 
    /**
     * 输出错误页面
     *
     * @param title    标题
     * @param message  内容
     * @param response HttpServletResponse
     */
    public static void outMessage(String title, String message, HttpServletResponse response) {
        response.setContentType("text/html;charset=UTF-8");
        try {
            PrintWriter writer = response.getWriter();
            writer.write("<!doctype html>");
            writer.write("<title>" + title + "</title>");
            writer.write("<h1 style=\"text-align: center\">" + title + "</h1>");
            if (message != null) {
                writer.write(message);
            }
            writer.write("<hr/><p style=\"text-align: center\">vincent File Server</p>");
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
}