FileController.java
11.2 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
package cn.fw.rp.web.controller;
import cn.fw.data.base.domain.common.Message;
import cn.fw.rp.common.enums.FileTypeEnums;
import cn.fw.rp.common.util.DateUtils;
import cn.fw.rp.dao.FileListDao;
import cn.fw.rp.dao.ProblemFileDao;
import cn.fw.rp.db.FileList;
import cn.fw.rp.db.ProblemFile;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.catalina.connector.ClientAbortException;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.UUID;
/**
* @author suchu
* @since 2018/5/9 10:59
*/
@Controller
@RequestMapping("/file")
public class FileController {
@Value("${upload.path}")
String uploadPath;
@Autowired
FileListDao dao;
@Autowired
ProblemFileDao problemFileDao;
public static void main(String[] args) throws IOException {
Thumbnails.of("F:\\RP_UPLOAD\\2018\\05\\09\\1db414949be24c3d9de479d2cbfa4c81.jpg")
.size(100, 100).toFile(new File("F:\\\\RP_UPLOAD\\test1.jpg"));
}
public String datePath() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
return sdf.format(DateUtils.getNow());
}
@RequestMapping("/video/{fileId}")
public void videoView(@PathVariable String fileId, HttpServletResponse response, HttpServletRequest request, @RequestHeader(value = "range", required = false) String range) {
FileList fileList = dao.selectByFileId(fileId);
File file = null;
if (null != fileList) {
file = new File(fileList.getFilePath());
if (!file.exists()) {
response.setStatus(204);//NO content
return;
}
}
//文件目录
// File music = new File("E:\\CloudMusic\\林子祥 - 街头霸王榜.mp3");
//开始下载位置
long startByte = 0;
//结束下载位置
long endByte = file.length() - 1;
//有range的话
if (range != null && range.contains("bytes=") && range.contains("-")) {
range = range.substring(range.lastIndexOf("=") + 1).trim();
String ranges[] = range.split("-");
try {
//判断range的类型
if (ranges.length == 1) {
//类型一:bytes=-2343
if (range.startsWith("-")) {
endByte = Long.parseLong(ranges[0]);
}
//类型二:bytes=2343-
else if (range.endsWith("-")) {
startByte = Long.parseLong(ranges[0]);
}
}
//类型三:bytes=22-2343
else if (ranges.length == 2) {
startByte = Long.parseLong(ranges[0]);
endByte = Long.parseLong(ranges[1]);
}
} catch (NumberFormatException e) {
startByte = 0;
endByte = file.length() - 1;
}
}
//要下载的长度(为啥要加一问小学数学老师去)
long contentLength = endByte - startByte + 1;
//文件名
String fileName = file.getName();
//文件类型
String contentType = request.getServletContext().getMimeType(fileName);
//各种响应头设置
//参考资料:https://www.ibm.com/developerworks/cn/java/joy-down/index.html
//坑爹地方一:看代码
response.setHeader("Accept-Ranges", "bytes");
//坑爹地方二:http状态码要为206
response.setStatus(response.SC_PARTIAL_CONTENT);
response.setContentType(contentType);
response.setHeader("Content-Type", contentType);
//这里文件名换你想要的,inline表示浏览器直接实用(我方便测试用的)
//参考资料:http://hw1287789687.iteye.com/blog/2188500
response.setHeader("Content-Disposition", "inline;filename=test.mp3");
response.setHeader("Content-Length", String.valueOf(contentLength));
//坑爹地方三:Content-Range,格式为
// [要下载的开始位置]-[结束位置]/[文件总大小]
response.setHeader("Content-Range", "bytes " + startByte + "-" + endByte + "/" + file.length());
BufferedOutputStream outputStream = null;
RandomAccessFile randomAccessFile = null;
//已传送数据大小
long transmitted = 0;
try {
randomAccessFile = new RandomAccessFile(file, "r");
outputStream = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[4096];
int len = 0;
randomAccessFile.seek(startByte);
//坑爹地方四:判断是否到了最后不足4096(buff的length)个byte这个逻辑((transmitted + len) <= contentLength)要放前面!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//不然会会先读取randomAccessFile,造成后面读取位置出错,找了一天才发现问题所在
while ((transmitted + len) <= contentLength && (len = randomAccessFile.read(buff)) != -1) {
outputStream.write(buff, 0, len);
transmitted += len;
//停一下,方便测试,用的时候删了就行了
// Thread.sleep(10);
}
//处理不足buff.length部分
if (transmitted < contentLength) {
len = randomAccessFile.read(buff, 0, (int) (contentLength - transmitted));
outputStream.write(buff, 0, len);
transmitted += len;
}
outputStream.flush();
response.flushBuffer();
randomAccessFile.close();
System.out.println("下载完毕:" + startByte + "-" + endByte + ":" + transmitted);
} catch (ClientAbortException e) {
System.out.println("用户停止下载:" + startByte + "-" + endByte + ":" + transmitted);
//捕获此异常表示拥护停止下载
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (randomAccessFile != null) {
randomAccessFile.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
@RequestMapping("/view/{fileId}")
public void view(@PathVariable String fileId, HttpServletResponse response, HttpServletRequest request) throws IOException {
FileList fileList = dao.selectByFileId(fileId);
if (null != fileList) {
File file = new File(fileList.getFilePath());
if (!file.exists()) {
response.setStatus(404);
return;
}
FileInputStream fileInputStream = new FileInputStream(file);
response.setContentType(fileList.getContentType());
response.setContentLength(fileInputStream.available());
byte buffer[] = new byte[4096];
ServletOutputStream outputStream = response.getOutputStream();
int length = fileInputStream.read(buffer);
while (length != -1) {
outputStream.write(buffer, 0, length);
length = fileInputStream.read(buffer);
}
outputStream.close();
} else {
response.setStatus(404);
System.out.println("无法下载...");
}
}
public int getFlag(String contentType) {
if (contentType.contains("image")) {
return FileTypeEnums.IMAGE.getType();
} else if (contentType.contains("video"))
return FileTypeEnums.VIDEO.getType();
else return FileTypeEnums.FILE.getType();
}
@RequestMapping("/image/thumb")
public void thumbnails(HttpServletResponse response, @RequestParam String fileId, @RequestParam(defaultValue = "200") Integer width, @RequestParam(defaultValue = "200") Integer height) throws IOException {
FileList fileList = dao.selectByFileId(fileId);
if (width > 2000)
width = 150;
if (height > 2000) {
height = 150;
}
if (null != fileList) {
File file = new File(fileList.getFilePath());
if (!file.exists()) {
response.setStatus(404);
} else {
response.setContentType(fileList.getContentType());
ServletOutputStream outputStream = response.getOutputStream();
Thumbnails.of(file).size(width, height).toOutputStream(outputStream);
outputStream.close();
}
} else {
response.setStatus(404);
}
}
@Transactional(rollbackFor = Exception.class)
@RequestMapping("/relate")
@ResponseBody
public Message relate(String fileId, String problemId) {
Assert.notNull(fileId, "file id must not be null");
Assert.notNull(problemId, "problem id must not be null");
ProblemFile problemFile = new ProblemFile();
problemFile.setFileId(fileId);
problemFile.setProblemId(problemId);
problemFileDao.insert(problemFile);
return Message.success("关联成功");
}
@Transactional(rollbackFor = Exception.class)
@PostMapping("/upload")
@ResponseBody
public Message upload(@RequestParam("file") MultipartFile file, @RequestParam(name = "flag", defaultValue = "3") Integer flag, HttpServletRequest request) throws IOException {
String contentType = file.getContentType();
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
Long fileLength = file.getSize();
//int flag = getFlag(contentType);
String fileName = file.getOriginalFilename();
String fileSuffix = fileName.substring(fileName.lastIndexOf("."));
FileList fileList = new FileList();
fileList.setContentType(contentType);
fileList.setFileId(uuid);
fileList.setUploadTime(DateUtils.getNow());
fileList.setFileName(fileName);
fileList.setFileLength(fileLength);
fileList.setFlag(flag);
// IOUtils.
File rootPath = new File(uploadPath);
if (!rootPath.exists()) {
rootPath.mkdir();
}
String datePath = datePath();
File outPath = new File(rootPath, datePath);
if (!outPath.exists()) {
outPath.mkdirs();
}
File outFile = new File(outPath, uuid + fileSuffix);
fileList.setFilePath(outFile.getAbsolutePath());
FileOutputStream fos = new FileOutputStream(outFile);
IOUtils.copy(file.getInputStream(), fos);
fos.flush();
fos.close();
dao.insert(fileList);
Message message = Message.success();
message.setData(fileList);
return message;
}
}