zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    使用Jquery EasyUi常见问题解决方案
    短信平台接口调用方法参考
    linux查找日志技巧
    Linux 上传 启动 删除...命令总结
    java 验证手机号码、电话号码(包括最新的电信、联通和移动号码)
    Web Services 中XML、SOAP和WSDL的一些必要知识
    Mac环境下配置PhpStorm
    Python爬虫刷回复
    Django和layim实现websocket
    Python爬虫刷回复
  • 原文地址:https://www.cnblogs.com/qinxiaowan/p/10536358.html
Copyright © 2011-2022 走看看