SpringBoot中的multipartResolver上传文件配置
目录
- multipartResolver上传文件配置
- 1、gradle配置
- 2、注册Bean
- SpringBoot MultipartResolver的坑
- 解决方案
multipartResolver上传文件配置
1、gradle配置
compile ('commons-io:commons-io:1.4') compile('commons-fileupload:commons-fileupload:1.2.1')
2、注册Bean
@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。我看通过源码可以看到
@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,
排除默认
spring: autoconfigure: exclude: org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration
自定义文件解析对象
@Bean(name = "multipartResolver") public MultipartResolver multipartResolver() { CommonsMultipartResolver resolver = new CommonsMultipartResolver(); resolver.setDefaultEncoding("UTF-8"); return resolver; }
以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。
赞 (0)