SpringBoot之文件上传

 

 1 package org.springboot.controller;
 2 
 3 import org.apache.logging.log4j.LogManager;
 4 import org.apache.logging.log4j.Logger;
 5 import org.springboot.constant.Constant;
 6 import org.springframework.stereotype.Controller;
 7 import org.springframework.web.bind.annotation.*;
 8 import org.springframework.web.multipart.MultipartFile;
 9 
10 import java.io.File;
11 import java.io.IOException;
12 
13 /**
14  * @Auther:GongXingRui
15  * @Date:2018/12/25
16  * @Description: 文件下载
17  **/
18 @Controller
19 public class FileUpload {
20     Logger logger = LogManager.getLogger(FileUpload.class);
21 
22     @GetMapping("/upload")
23     public String upload() {
24         return "upload";
25     }
26 
27     @PostMapping("/upload")
28     @ResponseBody
29     public String upload(@RequestParam("file") MultipartFile file) {
30         if (file.isEmpty()) {
31             return "上传失败,请选择文件";
32         }
33 
34         String fileName = file.getOriginalFilename();
35 //        String filePath = "C:/Temp/upload";
36         String filePath = Constant.CONFIG_PROPERTIES.getProperty("upload.path");
37         File dest = new File(filePath + File.separator + fileName);
38         //判断文件是否已经存在
39         if (dest.exists()) {
40             logger.info("文件已经存在 -> " + dest.getPath());
41         }
42         if (!dest.getParentFile().exists()) {
43             dest.getParentFile().mkdirs();
44             logger.info("目录不存在,自动创建 -> " + dest.getParentFile().getPath());
45         }
46         try {
47             file.transferTo(dest);
48             logger.info("上传成功");
49             return "上传成功";
50         } catch (IOException e) {
51             logger.error(e.toString(), e);
52         }
53         return "上传失败!";
54     }
55 }

 

posted @ 2018-12-28 10:56  星瑞  阅读(249)  评论(0编辑  收藏  举报