服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - SpringBoot中的multipartResolver上传文件配置

SpringBoot中的multipartResolver上传文件配置

2022-02-28 13:15闫-先生 Java教程

这篇文章主要介绍了SpringBoot中的multipartResolver上传文件配置,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

multipartResolver上传文件配置

1、gradle配置

?
1
2
compile ('commons-io:commons-io:1.4')
compile('commons-fileupload:commons-fileupload:1.2.1')

2、注册Bean

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

SpringBoot MultipartResolver的坑

在使用springBoot上传文件的时候,我们会用到MultipartResolver。我看通过源码可以看到

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Configuration
@ConditionalOnClass({ Servlet.class, StandardServletMultipartResolver.class,
  MultipartConfigElement.class })
@ConditionalOnProperty(prefix = "spring.http.multipart", name = "enabled", matchIfMissing = true)
@EnableConfigurationProperties(MultipartProperties.class)
public class MultipartAutoConfiguration {
 private final MultipartProperties multipartProperties;
 public MultipartAutoConfiguration(MultipartProperties multipartProperties) {
  this.multipartProperties = multipartProperties;
 }
 @Bean
 @ConditionalOnMissingBean({ MultipartConfigElement.class,
   CommonsMultipartResolver.class })
 public MultipartConfigElement multipartConfigElement() {
  return this.multipartProperties.createMultipartConfig();
 }
 @Bean(name = DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME)
 @ConditionalOnMissingBean(MultipartResolver.class)
 public StandardServletMultipartResolver multipartResolver() {
  StandardServletMultipartResolver multipartResolver = new StandardServletMultipartResolver();
  multipartResolver.setResolveLazily(this.multipartProperties.isResolveLazily());
  return multipartResolver;
 }

可以看出MultipartAutoConfiguration配置类,默认加载的是StandardServletMultipartResolver。

然而,我们往往会在项目中加入commons-fileupload依赖,加载的是CommonsMultipartResolver。此时同时使用两个,会产生冲突。

解决方案

1、使用SpringBoot 默认的StandardServletMultipartResolver,不依赖commons-fileupload。

2、使用commons-fileupload的CommonsMultipartResolver,

排除默认

?
1
2
3
spring:
  autoconfigure:
    exclude: org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration

自定义文件解析对象

?
1
2
3
4
5
6
@Bean(name = "multipartResolver")
public MultipartResolver multipartResolver() {
    CommonsMultipartResolver resolver = new CommonsMultipartResolver();
    resolver.setDefaultEncoding("UTF-8");
    return resolver;
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/u011110968/article/details/82856736

延伸 · 阅读

精彩推荐