CommonController.java
13.6 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
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
package com.skua.common.system.controller;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.skua.aop.annotation.CustomExceptionAnno;
import com.skua.common.system.util.FileUtil;
import com.skua.common.util.PicUtils;
import com.skua.core.api.vo.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.ModelAndView;
import lombok.extern.slf4j.Slf4j;
/**
* 用户表 前端控制器
*/
@Slf4j
@RestController
@RequestMapping("/sys/common")
public class CommonController {
@Value(value = "${skua.path.upload}")
private String uploadpath;
@Value(value = "${skua.path.chunk}")
private String chunkPath;
/**
* @return
* @Author 政辉
*/
@GetMapping("/403")
public Result<?> noauth() {
return Result.error("没有权限,请联系管理员授权");
}
@PostMapping(value = "/upload")
public Result<?> upload(HttpServletRequest request, HttpServletResponse response) {
Result<?> result = new Result<>();
try {
String ctxPath = uploadpath;
String fileName = null;
String bizPath = "files";
String nowday = new SimpleDateFormat("yyyyMMdd").format(new Date());
File file = new File(ctxPath + File.separator + bizPath + File.separator + nowday);
if (!file.exists()) {
file.mkdirs();// 创建文件根目录
}
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile mf = multipartRequest.getFile("file");// 获取上传文件对象
String orgName = mf.getOriginalFilename();// 获取文件名
fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.indexOf("."));
String savePath = file.getPath() + File.separator + fileName;
File savefile = new File(savePath);
FileCopyUtils.copy(mf.getBytes(), savefile);
String dbpath = bizPath + File.separator + nowday + File.separator + fileName;
if (dbpath.contains("\\")) {
dbpath = dbpath.replace("\\", "/");
}
result.setMessage(dbpath);
result.setSuccess(true);
} catch (IOException e) {
result.setSuccess(false);
result.setMessage(e.getMessage());
log.error(e.getMessage(), e);
}
return result;
}
@PostMapping(value = "/uploadCompress")
public Result<?> uploadCompression(HttpServletRequest request, HttpServletResponse response) {
Result<?> result = new Result<>();
try {
String ctxPath = uploadpath;
String fileName = null;
String bizPath = "files";
String nowday = new SimpleDateFormat("yyyyMMdd").format(new Date());
File file = new File(ctxPath + File.separator + bizPath + File.separator + nowday);
if (!file.exists()) {
file.mkdirs();// 创建文件根目录
}
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile mf = multipartRequest.getFile("file");// 获取上传文件对象
String orgName = mf.getOriginalFilename();// 获取文件名
fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.indexOf("."));
String savePath = file.getPath() + File.separator + fileName;
File savefile = new File(savePath);
//压缩图片
byte[] bytes = PicUtils.compressPicForScale(mf.getBytes(), 400);
FileCopyUtils.copy(bytes, savefile);
String dbpath = bizPath + File.separator + nowday + File.separator + fileName;
if (dbpath.contains("\\")) {
dbpath = dbpath.replace("\\", "/");
}
result.setMessage(dbpath);
result.setSuccess(true);
} catch (IOException e) {
result.setSuccess(false);
result.setMessage(e.getMessage());
log.error(e.getMessage(), e);
}
return result;
}
/**
* 预览图片
* 请求地址:http://localhost:8080/common/view/{user/20190119/e1fe9925bc315c60addea1b98eb1cb1349547719_1547866868179.jpg}
*
* @param request
* @param response
*/
@GetMapping(value = "/view/**")
public void view(HttpServletRequest request, HttpServletResponse response) {
// ISO-8859-1 ==> UTF-8 进行编码转换
String imgPath = extractPathFromPattern(request);
// 其余处理略
InputStream inputStream = null;
OutputStream outputStream = null;
try {
imgPath = imgPath.replace("..", "");
if (imgPath.endsWith(",")) {
imgPath = imgPath.substring(0, imgPath.length() - 1);
}
response.setContentType("image/jpeg;charset=utf-8");
String localPath = uploadpath;
String imgurl = localPath + File.separator + imgPath;
inputStream = new BufferedInputStream(new FileInputStream(imgurl));
outputStream = response.getOutputStream();
byte[] buf = new byte[1024];
int len;
while ((len = inputStream.read(buf)) > 0) {
outputStream.write(buf, 0, len);
}
response.flushBuffer();
} catch (IOException e) {
log.error("预览图片失败" + e.getMessage());
// e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
}
/**
* 下载文件
* 请求地址:http://localhost:8080/common/download/{user/20190119/e1fe9925bc315c60addea1b98eb1cb1349547719_1547866868179.jpg}
*
* @param request
* @param response
* @throws Exception
*/
@GetMapping(value = "/download/**")
public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
// ISO-8859-1 ==> UTF-8 进行编码转换
String filePath = extractPathFromPattern(request);
// 其余处理略
InputStream inputStream = null;
OutputStream outputStream = null;
try {
filePath = filePath.replace("..", "");
if (filePath.endsWith(",")) {
filePath = filePath.substring(0, filePath.length() - 1);
}
String localPath = uploadpath;
String downloadFilePath = localPath + File.separator + filePath;
File file = new File(downloadFilePath);
if (file.exists()) {
response.setContentType("application/force-download");// 设置强制下载不打开
response.addHeader("Content-Disposition", "attachment;fileName=" + new String(file.getName().getBytes("UTF-8"), "iso-8859-1"));
inputStream = new BufferedInputStream(new FileInputStream(file));
outputStream = response.getOutputStream();
byte[] buf = new byte[1024];
int len;
while ((len = inputStream.read(buf)) > 0) {
outputStream.write(buf, 0, len);
}
response.flushBuffer();
}
} catch (Exception e) {
log.info("文件下载失败" + e.getMessage());
// e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* @param modelAndView
* @return
* @功能:pdf预览Iframe
*/
@RequestMapping("/pdf/pdfPreviewIframe")
public ModelAndView pdfPreviewIframe(ModelAndView modelAndView) {
modelAndView.setViewName("pdfPreviewIframe");
return modelAndView;
}
/**
* 把指定URL后的字符串全部截断当成参数
* 这么做是为了防止URL中包含中文或者特殊字符(/等)时,匹配不了的问题
*
* @param request
* @return
*/
private static String extractPathFromPattern(final HttpServletRequest request) {
String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
String bestMatchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
return new AntPathMatcher().extractPathWithinPattern(bestMatchPattern, path);
}
@PostMapping("/shardUpload")
@CustomExceptionAnno(description = "断点续传-上传分片文件")
public Result<?> shardUploads(@RequestParam("file") MultipartFile multipartFile,
@RequestParam("fileType") String fileType,
@RequestParam("md5") String md5,
@RequestParam("fileName") String fileName,
@RequestParam(name = "currentChunk", defaultValue = "-1") Integer currentChunk) throws Exception {
Result<?> result = new Result<>();
String dirPath = chunkPath + File.separator + fileType + File.separator + md5;
String fileName0 = fileName.split("\\.")[0];
if (FileUtil.mkDirs(dirPath)) {
File tmpFolder = new File(dirPath + File.separator + fileName0 + ".chunk");
if (!tmpFolder.exists()) {
tmpFolder.mkdirs();
}
File chunkFile = new File(dirPath + File.separator + fileName0 + ".chunk" + File.separator + currentChunk);
if (!chunkFile.exists()) {
multipartFile.transferTo(chunkFile);
}
}
return result;
}
@CustomExceptionAnno(description = "断点续传-根据文件名判断是否存在")
@GetMapping("/isExist")
public Result<Object> isExistCtrl(@RequestParam("fileType") String fileType, @RequestParam("md5") String md5, @RequestParam("fileName") String fileName) {
Result<Object> result = new Result<>();
File dirFile = new File(chunkPath + File.separator + fileType + File.separator + md5);
List<Integer> list = new ArrayList<>();
if (dirFile.exists()) {
File[] folders = dirFile.listFiles();
if (folders != null && folders.length != 0) {
for (File folder : folders) {
// 判断是否存在文件夹,即已经上传的部分
if (folder.isDirectory()) {
File[] chunkFiles = folder.listFiles();
if (chunkFiles != null && chunkFiles.length != 0) {
for (File file : chunkFiles) {
list.add(Integer.parseInt(file.getName()));
}
}
}
}
}
if (list.size() == 0) {
result.setMessage("文件已上传");
result.setResult(File.separator + fileType + File.separator + md5 + File.separator + fileName);
} else {
result.setResult(list);
result.setMessage("文件仅上传部分");
}
} else {
result.setCode(201);
result.setMessage("文件未上传");
}
return result;
}
@GetMapping("/shardMerge")
@CustomExceptionAnno(description = "断点续传-分片合并")
public Result<String> shardMergeCtrl(@RequestParam("fileType") String fileType, @RequestParam("md5") String md5, @RequestParam("fileName") String fileName) {
Result<String> result = new Result<>();
String dirPath = chunkPath + File.separator + fileType + File.separator + md5;
String fileName0 = fileName.split("\\.")[0];
String chunkFolder = dirPath + File.separator + fileName0 + ".chunk";
File chunkFolderFile = new File(chunkFolder);
File[] files = chunkFolderFile.listFiles();
File mergeFile = new File(dirPath + File.separator + fileName);
if (files != null) {
List<File> fileList = Arrays.asList(files);
FileUtil.shardMerge(fileList, mergeFile);
FileUtil.delFile(chunkFolderFile);
result.success("分片合并成功");
} else {
result.error500("分片合并失败");
}
result.setResult(File.separator + fileType + File.separator + md5 + File.separator + fileName);
return result;
}
}