FileIOUtil.java
2.93 KB
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
package cn.com.glsx.admin.modules.utils;
import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
/**
* 项目名:ne-shield-trialdrive-admin
* 包名: cn.com.glsx.admin.modules.utils
* 作者: Yanglinlong
* 日期: 2021/5/18 14:23
*/
public class FileIOUtil {
public enum MimeType {
STREAM("application/octet-stream", "jpg"),
PDF("application/pdf", "pdf"),
ZIP("application/zip", "zip"),
RAR("application/zip", "rar"),
EXCEL2003("application/vnd.ms-excel", "xls"),
EXCEL2007("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "xlsx"),
EXE("application/octet-stream", "exe"),
TXT("text/plain", "txt"),
JAVA("text/plain", "java"),
PYTHON("text/plain", "py"),
JAVASCRIPT("text/plain", "js"),
CSS("text/plain", "css"),
JPG("application/x-jpg", "jpg"),
JPEG("image/jpeg", "jpg"),
GIF("image/gif", "gif"),
PNG("application/x-png", "png");
private String contentType;
public final static String CHARSET = "UTF-8";
private String suffix;
public String getContentType() {
return contentType + ";charset=" + CHARSET;
}
private MimeType(String contentType, String suffix) {
this.contentType = contentType;
this.suffix = suffix;
}
public static String getMimeSuffix(String contentType) {
for (MimeType mimeType : MimeType.values()) {
if (mimeType.getContentType().equals(contentType)) {
return mimeType.getSuffix();
}
}
return null;
}
public String getSuffix() {
return suffix;
}
}
public static void download(InputStream input, MimeType mime, String fileName, HttpServletResponse response) throws IOException {
if (input == null) {
return;
}
response.setContentType(mime.getContentType());
response.setHeader("Set-Cookie", "fileDownload=true; path=/");
String encodeFileName = fileName + "." + mime.getSuffix();
response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(encodeFileName, "UTF-8"));
long length = input.available();
if (length != -1) {
response.setContentLength((int) length);
}
ServletOutputStream output = response.getOutputStream();
IOUtils.copy(input, output);
output.flush();
}
public static String getMultipartFileType(MultipartFile multipartFile) {
if (multipartFile == null) {
return null;
}
String contentType = multipartFile.getContentType();
return MimeType.getMimeSuffix(contentType);
}
}