springboot 保存文件


保存图片

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
@ResponseBody
@RequestMapping(value = "/img-upload", method = RequestMethod.POST)
private Map<String, Object> imgUpload(@RequestParam("files") MultipartFile[] files, HttpServletRequest request) throws Exception {

// 获得物理路径webapp所在路径
String pathRoot = request.getSession().getServletContext().getRealPath("");
pathRoot = request.getSession().getServletContext().getRealPath("resources/upload/images/");

File fileDir = new File(pathRoot);
if (!fileDir.exists()) {
// 递归生成文件夹
fileDir.mkdirs();
}
String path = "";
List<String> imgs = new ArrayList<>();
if (files != null && files.length > 0) {

for (int i = 0; i < files.length; i++) {
MultipartFile file = files[i];

// 生成uuid作为文件名称
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
// 获得文件类型(可以判断如果不是图片,禁止上传)
String contentType = file.getContentType();
// 获得文件后缀名称
String imageName = contentType.substring(contentType.indexOf("/") + 1);
path = uuid + "." + imageName;
file.transferTo(new File(pathRoot + path));


// 获取当前项目的完整url
String requestURL = request.getRequestURL().toString();
// 获取当前项目的请求路径uri
String requestURI = request.getRequestURI();
// 得到去掉了uri的路径
String url = requestURL.substring(0, requestURL.length()-requestURI.length() + 1);
// 返回
// return url + newFileName;
imgs.add(url+ "upload/images/" + path);
}

}

Map<String, Object> result = new HashMap<>();
result.put("errno", 0);
result.put("data", imgs);

return result;
}

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×