SpringBoot + MultipartFile 實現文件上傳以及文件轉移的功能以及配置全局捕獲上傳文件過大異常


2019-03-15

話不多說直接上代碼

application.yml:因為Linux環境與Windows環境路徑不一致,暫時用Windows環境測試

server:
  port: 8891

#文件上傳Windows
upload:
  path:
    #臨時目錄
    temporary: E:/upload/temporary/
    #正式目錄
    formal: E:/upload/formal/
  multipart:
    #單個文件最大內存
    maxFileSize: 512KB
    #所有文件最大內存
    maxRequestSize: 5MB

#文件上傳Linux
#upload:
#  path:
#    #臨時目錄
#    temporary: /usr/upload/temporary/
#    #正式目錄
#    formal: /usr/upload/formal/
#  multipart:
#    #單個文件最大內存
#    maxFileSize: 512KB
#    #所有文件最大內存
#    maxRequestSize: 5MB

spring:
  resources:
    #靜態資源訪問
    static-locations: file:${upload.path.temporary},file:${upload.path.formal}

 FilesConfig:讀取配置文件中文件上傳配置

 6 
 7 /**
 8  * @Author Qin
 9  * @Date 2019-03-11 13:21
10  */
11 @Component
12 @Data
13 public class FilesConfig {
14 
15     /**
16      * 單文件上傳最大內存
17      */
18     @Value("${upload.multipart.maxFileSize}")
19     private String maxFileSize;
20 
21     /**
22      * 多文件上傳最大內存
23      */
24     @Value("${upload.multipart.maxRequestSize}")
25     private String maxRequestSize;
26 
27     /**
28      * 文件上傳臨時目錄
29      */
30     @Value("${upload.path.temporary}")
31     private String temporaryPath;
32 
33     /**
34      * 文件上傳正式目錄
35      */
36     @Value("${upload.path.formal}")
37     private String formalPath;
38 }

FilesUploadService:文件上傳Service,返回文件名稱

 12 /**
 13  * 文件上傳
 14  *
 15  * @Author Qin
 16  * @Date 2019-03-11 13:28
 17  */
 18 public class UploadService {
 19     /**
 20      * 文件上傳時間
 21      *
 22      * @return
 23      */
 24     public static String getUploudTime() {
 25         Date date = new Date();
 26         DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
 27         return df.format(date);
 28     }
 29 
 30     /**
 31      * 給原文件取新的名稱
 32      *
 33      * @param fileOriginName
 34      * @return
 35      */
 36     public static String getFileName(String fileOriginName) {
 37         return UUID.randomUUID().toString().replace("-", "") + fileOriginName.substring(fileOriginName.lastIndexOf("."));
 38     }
 39 
 40     /**
 41      * 單文件上傳
 42      *
 43      * @param file 文件
 44      * @param path 文件上傳路徑
 45      * @return
 46      * @throws IOException
 47      */
 48     public static String uploadOne(MultipartFile file, String path) throws IOException {
 49         String uploudTime = UploadService.getUploudTime();
 50         //新的文件存放路徑加上新的文件名
 51         String newPath = path + uploudTime + "/" + UploadService.getFileName(file.getOriginalFilename());
 52         File file1 = new File(newPath);
 53         //判斷文件目錄是否存在
 54         if (!file1.getParentFile().exists()) {
 55             //創建文件存放目錄
 56             //無論是幾個/,都是創建一個文件夾
 57             //mkdirs(): 創建多層目錄,如:E:/upload/2019
 58             //mkdir(): 只創建一層目錄,如:E:upload
 59             //如果不加這一行不會創建新的文件夾,會報系統找不到路徑
 60             file1.getParentFile().mkdirs();
 61         }
 62         //存儲文件
 63         file.transferTo(file1);
 64         //去掉目錄名,保留文件總體路徑,通過該路徑訪問圖片
 65         String filename = newPath.substring(newPath.lastIndexOf(path)).replace(path, "");
 66         return filename;
 67     }
 68 
 69     /**
 70      * 多文件上傳
 71      *
 72      * @param files 文件
 73      * @param path  文件上傳路徑
 74      * @return
 75      * @throws IOException
 76      */
 77     public static String uploadMore(MultipartFile[] files, String path) throws IOException {
 78         //多文件文件名
 79         String uploadName = null;
 80         String uploudTime = UploadService.getUploudTime();
 81         for (MultipartFile file : files) {
 82             //新的文件存放路徑加上新的文件名
 83             String newPath = path + uploudTime + "/" + UploadService.getFileName(file.getOriginalFilename());
 84             File file1 = new File(newPath);
 85             //判斷文件目錄是否存在
 86             if (!file1.getParentFile().exists()) {
 87                 //創建文件存放目錄
 88                 //無論是幾個/,都是創建一個文件夾
 89                 //mkdirs(): 創建多層目錄,如:E:/upload/2019
 90                 //mkdir(): 只創建一層目錄,如:E:upload
 91                 //如果不加這一行不會創建新的文件夾,會報系統找不到路徑
 92                 file1.getParentFile().mkdirs();
 93             }
 94             //存儲文件
 95             file.transferTo(file1);
 96             if (uploadName == null) {
 97                 uploadName = newPath.substring(newPath.lastIndexOf(path)).replace(path, "");
 98             } else {
 99                 uploadName = uploadName + "," + newPath.substring(newPath.lastIndexOf(path)).replace(path, "");
100             }
101         }
102         return uploadName;
103     }
104 }

 FilesUploadController:文件上傳Controller同時包含文件轉移

 1 /**
 2  * @Author Qin
 3  * @Date 2019-03-11 10:54
 4  */
 5 @RestController
 6 @RequestMapping("/api/file")
 7 public class FilesUploadController {
 8 
 9     @Autowired
10     private FilesConfig filesConfig;
11 
12     /**
13      * 設置文件上傳大小:在配置文件中限定
14      * @return
15      */
16     @Bean
17     public MultipartConfigElement multipartConfigElement() {
18         MultipartConfigFactory factory = new MultipartConfigFactory();
19         //單個文件最大
20         factory.setMaxFileSize(filesConfig.getMaxFileSize());
21         //設置總上傳數據總大小
22         factory.setMaxRequestSize(filesConfig.getMaxRequestSize());
23         return factory.createMultipartConfig();
24     }
25 
26     /**
27      * 單文件上傳
28      * @param file
29      * @return
30      * @throws IOException
31      */
32     @PostMapping("/uploadOne")
33     public JsonResult uploadOne(MultipartFile file) throws IOException {
34         String uploadOne = UploadService.uploadOne(file, filesConfig.getTemporaryPath());
35         return ResponseResult.Success(ResultCodeEnums.SUCCESS,uploadOne);
36     }
37 
38     /**
39      * 多文件上傳
40      * @param files
41      * @return
42      * @throws IOException
43      */
44     @PostMapping("/uploadMore")
45     public JsonResult uploadMore(MultipartFile[] files) throws IOException {
46         String uploadMore = UploadService.uploadMore(files, filesConfig.getTemporaryPath());
47         String[] uploadMores = uploadMore.split(",");
48         return ResponseResult.Success(ResultCodeEnums.SUCCESS,uploadMores);
49     }
50 
51     /**
52      * 文件轉移:適用於多文件以及單文件
53      * @param uploadPath
54      * @return
55      * @throws IOException
56      */
57     @PostMapping("/change")
58     public JsonResult filesChange(@RequestBody String [] uploadPath) throws IOException {
59         //循環遍歷傳來的String數組
60         for (String u : uploadPath) {
61             //拿到臨時目錄的文件
62             String path = filesConfig.getTemporaryPath() + u;
63             File file = new File(path);
64             //File類型轉換為MultipartFile類型
65             MultipartFile multipartFile = new MockMultipartFile(file.getName(), new FileInputStream(file));
66             //正式目錄名與文件名生成一個新的路徑
67             String newPath = filesConfig.getFormalPath() + u;
68             File newFile = new File(newPath);
69             //判斷文件目錄是否存在
70             if (!newFile.getParentFile().exists()) {
71                 //創建文件存放目錄
72                 //無論是幾個/,都是創建一個文件夾
73                 //mkdirs(): 創建多層目錄,如:E:/upload/2019
74                 //mkdir(): 只創建一層目錄,如:E:upload
75                 //如果不加這一行不會創建新的文件夾,會報系統找不到路徑
76                 newFile.getParentFile().mkdirs();
77             }
78             //存儲文件
79             multipartFile.transferTo(newFile);
80             //去掉目錄名,保留文件總體路徑,通過該路徑訪問圖片
81         }
82         return ResponseResult.Success(ResultCodeEnums.SUCCESS);
83     }
84 }

 

文件過大異常捕獲

 1 /**
 2  * @Author Qin
 3  * @Date 2019-03-13 11:46
 4  */
 5 @RestControllerAdvice
 6 public class MyExceptionHandler {
 7 
 8     @Autowired
 9     private FilesConfig filesConfig;
10 
11     /**
12      * 文件上傳過大返回異常信息
13      * @param e
14      * @return
15      */
16     @ExceptionHandler(MaxUploadSizeExceededException.class)
17     public JsonResult handleMaxUploadSizeExceededException(MaxUploadSizeExceededException e) {
18         String message = ResultCodeEnums.FAIL_10006.msg()
19                 .replace("${size}",filesConfig.getMaxFileSize())
20                 .replace("${allsize}",filesConfig.getMaxRequestSize());
21         ResultCodeEnums.FAIL_10006.setMsg(message);
22         return ResponseResult.Fail(ResultCodeEnums.FAIL_10006);//FAIL_10006("10006","單文件最大不可以超過${size},多文件最大不可以超過${allsize}"),
23     }
24 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM