SpringBoot中的multipartResolver上传⽂件配置
⽬录
multipartResolver上传⽂件配置
1、gradle配置
2、注册Bean
SpringBootMultipartResolver的坑
解决⽅案
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;spring怎么读取properties
}
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 ateMultipartConfig();
}
@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;
}
以上为个⼈经验,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论