Spring Boot 上传文件

Spring Boot 上传文件

依赖jar

pom.xml

1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>

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
@RestController
@RequestMapping
public class UploadController {

@RequestMapping(value = "/uploadDelta.do")
@ResponseBody
public Map<String, Object> updateDelta(MultipartFile file) {
Map<String, Object> result = new HashMap<String, Object>();

String rootFilePath = uploadpath;

//文件最后保存的目录
String path_save =
"/" + paramer.getProjectId() + "/" + deltaEntity.getId() + "/";/**文件保存路径(没有文件名称)**/
String saveFilePath = rootFilePath + path_save;
File allPathFile = new File(saveFilePath);
if (!allPathFile.exists()) {
allPathFile.mkdirs();
logger.info("创建文件夹,路径:" + allPathFile);
}

Map<String, String> map = new HashMap<String, String>();

String fileName = paramer.getFile().getOriginalFilename(); //获取文件名
String[] fileNameSplit = fileName.split("\\.");//获取文件拓展名
String compress = fileNameSplit[fileNameSplit.length - 1];

String randomFilename = UUID.randomUUID().toString() + "." + compress;
File destFile = new File(saveFilePath + randomFilename);//随机生成的文件名

logger.info("文件保存路径:" + saveFilePath + randomFilename);

try {//文件写入硬盘
paramer.getFile().transferTo(new File(saveFilePath + randomFilename));
} catch (Exception e) {
e.printStackTrace();
logger.error("文件保存到硬盘失败");
result.put("status", ResultParams.PROJECT_FAIL_STATUS);
result.put("msg", "文件上传失败");
return result;
}


return null;
}
}

大文件上传异常

spring boot 限制一次表单提交总共文件的最大大小为10MB,每一个文件的大小为1MB.

1
2
3
4
MultipartProperties

private String maxFileSize = "1Mb";
private String maxRequestSize = "10Mb";

解决方法

  1. 直接通过配置文件解决

    application.properties

    1
    2
    3
    4
    spring.http.multipart.max-request-size=1024MB 
    # 大小设置为1G
    spring.http.multipart.max-file-size=1024MB
    # 大小设置为1G
  2. 通过代码层级修改文件上传大小限制

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    import org.springframework.web.multipart.MultipartResolver;
    import org.springframework.web.multipart.commons.CommonsMultipartResolver;


    @Bean(name = "multipartResolver")
    public MultipartResolver multipartResolver() {
    CommonsMultipartResolver resolver = new CommonsMultipartResolver();
    resolver.setDefaultEncoding("UTF-8");
    resolver.setResolveLazily(true);//resolveLazily属性启用是为了推迟文件解析,以在在UploadAction中捕获文件大小异常
    resolver.setMaxInMemorySize(40960);
    resolver.setMaxUploadSize(500 * 1024 * 1024);//上传文件大小 50M 50*1024*1024
    return resolver;
    }

在spring boot 1.5.4版本中可以直接通过 @Bean("multipartResolver") 进行注入。

注意点