[JavaWeb] SpringBoot上传文件

 1 @PostMapping("/upload_file")
 2     public Map<String, Object> uploadFile(
 3             @RequestParam(value = "upload_file", required = false) MultipartFile uploadFile
 4     ) {
 5         Map<String, Object> resultJson = new LinkedHashMap<>();
 6         if (uploadFile == null || uploadFile.isEmpty()) {
 7             resultJson.put("code", -1);
 8             resultJson.put("msg", "上传文件不得为空");
 9             return resultJson;
10         }
11         String originalFilename = uploadFile.getOriginalFilename(); // 上传的文件原名称
12         String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1) ; // 取后缀名
13 
14         String newFileName = DigestUtils.md5DigestAsHex((System.currentTimeMillis() + originalFilename).getBytes()) + "." + suffix; // 新的文件名
15         try {
16             String fileRootPath = ResourceUtils.getURL("classpath:").getPath() + "/public/"; // 取项目的 classpath目录的绝对路径下的 public文件夹下
17             String filePath = fileRootPath + "/upload/" + newFileName;
18 
19             File file1 = new File(filePath);
20             if (!file1.exists()) file1.mkdirs(); // 要是目录不存在,创建一个
21             uploadFile.transferTo(file1); // 保存起来
22 
23             resultJson.put("code", 1);
24             resultJson.put("data", "/upload/" + newFileName);
25             resultJson.put("msg", "保存成功");
26         }catch (Exception e) {
27             e.printStackTrace();
28             resultJson.put("code", 0);
29             resultJson.put("msg", e.getMessage());
30         }
31         return resultJson;
32     }

 

posted @ 2020-10-21 15:50  Xiwi  阅读(127)  评论(0编辑  收藏  举报