组件

  • cn.hutool.core.util.ZipUtil

配置文件 application.yaml

1
2
3
4
5
6
solution:
file:
prefix: "/usr/local/item"
picFilePath: "/pic/"
commonFilePath: "/common/"
zipFilePath: "/zip/"

代码

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
import cn.hutool.core.util.ZipUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.net.URLEncoder;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/file")
@Api(tags = "文件管理")
@Slf4j
public class FileController {

@Value("${solution.file.prefix}")
private String preFilePath;

@Value("${solution.file.picFilePath}")
private String picFilePath;

@Value("${solution.file.commonFilePath}")
private String commonFilePath;

@Value("${solution.file.zipFilePath}")
private String zipFilePath;

@PostMapping("/uploadFile")
@ApiOperation("上传")
public Result<Object> uploadFile(@RequestParam("file") MultipartFile[] file, @RequestParam("type") String type) {
if (ObjectUtils.isEmpty(type) || ObjectUtils.isEmpty(file)) {
return new Result<>().error("缺少请求参数");
}
String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));
String filePath;
switch (type) {
case "1": { // 图片目录
filePath = picFilePath;
break;
}
default: { // 未定义则放入公共目录
filePath = commonFilePath;
break;
}
}
String fileUrlWithOutPrefix = String.format("%s%s%s", filePath, currentTime, "/");
String fileUrl = String.format("%s%s", preFilePath, fileUrlWithOutPrefix);
File fileMkdir = new File(fileUrl);
if (!fileMkdir.exists()) {
boolean mkdirs = fileMkdir.mkdirs();
}
List<String> fileUrlList = new ArrayList<>();
try {
for (MultipartFile f : file) {
File upload = new File(fileUrl + f.getOriginalFilename());
f.transferTo(upload);
fileUrlList.add(fileUrlWithOutPrefix + f.getOriginalFilename());
}
return new Result<>().ok(fileUrlList);
} catch (Exception e) {
e.printStackTrace();
}
return new Result<>().error("上传失败");
}

@GetMapping("/download")
@ApiOperation("下载文件")
public void downloadNoticeFile(@RequestParam String path, HttpServletResponse response) {
String fullPath = Paths.get(preFilePath, path).toString();
try {
// 防止用户下载的文件目录含有 ../
Path normalizedPath = Paths.get(fullPath).normalize();
if (!fullPath.equals(normalizedPath.toString())) {
throw new RuntimeException(String.format("File path [%s] forbidden", fullPath));
}
File file = new File(fullPath);
if (!file.exists()) {
throw new RuntimeException(String.format("File path [%s] not found", fullPath));
}
response.setContentType("application/msword;charset=UTF-8");
// 解决中文文件名的问题,前端需要在响应头中获取filename,并decode
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
response.setContentLength((int) file.length());
try (FileInputStream inputStream = new FileInputStream(file);
ServletOutputStream outputStream = response.getOutputStream()) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
}
} catch (InvalidPathException e) {
log.error("Invalid file path: {}", e.getMessage(), e);
throw e;
} catch (Exception e) {
log.error("", e);
}
}

@GetMapping("/downloadZip")
@ApiOperation("下载文件压缩包")
public void downloadZipFile(@RequestParam("path") String path, HttpServletResponse response) {
try {
String[] paths = path.split(",");
List<File> fileList = new ArrayList<>();
for (String p : paths) {
String fullPath = Paths.get(preFilePath, p).toString();
Path normalizedPath = Paths.get(fullPath).normalize();
if (!fullPath.equals(normalizedPath.toString())) {
throw new RuntimeException(String.format("File path [%s] forbidden", fullPath));
}
File file = new File(fullPath);
if (!file.exists()) {
throw new RuntimeException(String.format("File path [%s] not found", fullPath));
}
fileList.add(file);
}

String zipFileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")) + ".zip";
String zipFileFullPath = Paths.get(preFilePath, zipFilePath, zipFileName).toString();

// 压缩文件
ZipUtil.zip(new File(zipFileFullPath), false, fileList.toArray(new File[0]));

// 设置响应头
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment;filename=" + zipFileName);
response.setContentLength((int) new File(zipFileFullPath).length());

// 将压缩文件写入响应输出流
try (FileInputStream inputStream = new FileInputStream(zipFileFullPath);
ServletOutputStream outputStream = response.getOutputStream()) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
}

// 删除临时生成的ZIP文件
File zipFile = new File(zipFileFullPath);
if (zipFile.exists()) {
zipFile.delete();
}
} catch (InvalidPathException e) {
log.error("Invalid file path: {}", e.getMessage(), e);
throw e;
} catch (Exception e) {
log.error("", e);
}
}
}