从零搭建自己的SpringBoot后台框架(十六)

释放双眼,带上耳机,听听看~!

在一个系统中,文件上传模块肯定是少不了的,例如头像上传,展示轮播图等等,所以本章我们来添加上传文件功能

一:添加commons-fileupload依赖

打开pom文件添加


1
2
3
4
5
6
1<dependency>
2   <groupId>commons-fileupload</groupId>
3   <artifactId>commons-fileupload</artifactId>
4   <version>1.3.1</version>
5</dependency>
6

二:添加系统变量

打开core→constant文件,添加文件保存路径


1
2
3
1//文件上传储存的地址
2public static final String SAVEFILEPATH = "F://img";
3

三:添加文件上传限制

创建core→configurer→MultipartConfigurer.java


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
1package com.example.demo.core.configurer;
2
3import org.springframework.boot.web.servlet.MultipartConfigFactory;
4import org.springframework.context.annotation.Bean;
5import org.springframework.context.annotation.Configuration;
6
7import javax.servlet.MultipartConfigElement;
8
9@Configuration
10public class MultipartConfigurer {
11
12    @Bean
13    public MultipartConfigElement multipartConfigElement(){
14        MultipartConfigFactory factory=new MultipartConfigFactory();
15        factory.setMaxFileSize("10MB");
16        factory.setMaxRequestSize("10MB");
17        return factory.createMultipartConfig();
18    }
19}
20

四:创建文件上传工具类

创建core→utils→UploadActionUtil.java


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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
1package com.example.demo.core.utils;
2
3import com.example.demo.core.constant.ProjectConstant;
4import org.springframework.web.multipart.MultipartFile;
5import org.springframework.web.multipart.MultipartHttpServletRequest;
6import org.springframework.web.multipart.commons.CommonsMultipartResolver;
7
8import javax.servlet.http.HttpServletRequest;
9import java.io.File;
10import java.text.SimpleDateFormat;
11import java.util.*;
12
13/**
14 * @author phubing
15 * 文件上传控制器
16 */
17public class UploadActionUtil {
18
19   public static List<String> uploadFile(HttpServletRequest request) throws Exception {
20      List<String> list = new ArrayList<>();
21      CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
22            request.getSession().getServletContext());
23      if (multipartResolver.isMultipart(request)) {
24         MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
25         Iterator<String> iterator = multiRequest.getFileNames();
26         while (iterator.hasNext()) {
27            // 取得上传文件
28            MultipartFile file = multiRequest.getFile(iterator.next());
29            if (file != null) {
30               // 取得当前上传文件的文件名称
31               String myFileName = file.getOriginalFilename();
32               // 如果名称不为“”,说明该文件存在,否则说明该文件不存在
33               if (myFileName.trim() != "") {
34                  String fileTyps = myFileName.substring(myFileName.lastIndexOf("."));
35                  // String tempName="demo"+fileTyps;
36                  String tempName = UUID.randomUUID().toString() + fileTyps;
37                  // 创建文件夹
38                  String folderPath = ProjectConstant.SAVEFILEPATH + File.separator + folderName();
39                  File fileFolder = new File(folderPath);
40                  if (!fileFolder.exists() && !fileFolder.isDirectory()) {
41                     fileFolder.mkdir();
42                  }
43                  File uploadFile = new File(folderPath + File.separator + tempName);
44                  file.transferTo(uploadFile);
45                  myFileName = folderName() + File.separator + tempName;
46                  list.add(ProjectConstant.SAVEFILEPATH + "//" + myFileName);
47               }
48            }
49         }
50      }
51      return list;
52   }
53
54   /**
55    * 得年月日的文件夹名称
56    *
57    * @return
58    */
59   public static String getCurrentFilderName()  throws Exception{
60      Calendar now = Calendar.getInstance();
61      return now.get(Calendar.YEAR) + "" + (now.get(Calendar.MONTH) + 1) + "" + now.get(Calendar.DAY_OF_MONTH);
62   }
63
64   /**
65    * 创建文件夹
66    *
67    * @param filderName
68    */
69   public static void createFilder(String filderName) throws Exception {
70      File file = new File(filderName);
71      // 如果文件夹不存在则创建
72      if (!file.exists() && !file.isDirectory()) {
73         file.mkdirs();
74      }
75   }
76
77   /**
78    * 文件扩展名
79    *
80    * @param fileName
81    * @return
82    */
83   public static String extFile(String fileName)  throws Exception{
84      return fileName.substring(fileName.lastIndexOf("."));
85   }
86
87   /**
88    * 当前日期当文件夹名
89    *
90    * @return
91    */
92   public static String folderName() throws Exception {
93      SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
94      String str = sdf.format(new Date());
95      return str;
96   }
97}
98

五:创建UploadFileController


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
1package com.example.demo.controller;
2
3import com.example.demo.core.ret.RetResponse;
4import com.example.demo.core.ret.RetResult;
5import com.example.demo.core.utils.UploadActionUtil;
6import org.springframework.web.bind.annotation.PostMapping;
7import org.springframework.web.bind.annotation.RequestMapping;
8import org.springframework.web.bind.annotation.RestController;
9
10import javax.servlet.http.HttpServletRequest;
11import java.util.List;
12
13@RestController
14@RequestMapping("/uploadFile")
15public class UploadFileController {
16
17    @PostMapping("/upload")
18    public RetResult<List<String>> upload(HttpServletRequest httpServletRequest) throws Exception {
19        List<String> list = UploadActionUtil.uploadFile(httpServletRequest);
20        return RetResponse.makeOKRsp(list);
21    }
22}
23

六:测试

打开postman

输入localhost:8080/uploadFile/upload

注意:请求参数如下

返回值为文件存储的路径

 

打开设置好的存储路径

ok,上传成功

给TA打赏
共{{data.count}}人
人已打赏
安全技术

C++ explicit关键字

2022-1-11 12:36:11

安全运维

Linux从用户层到内核层系列 - 开源项目之Libxml2

2021-8-18 16:36:11

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索