微前端架构如何改变企业的开发模式与效率提升
1260
2022-11-29
SpringBoot中的multipartResolver上传文件配置
目录multipartResolver上传文件配置1、gradle配置2、注册BeanSpringBoot 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, StandardServletTFMRCjxWMultipartResolver.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,
CommonsMultipartResolTFMRCjxWver.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.MultipartAutoConfigurathttp://ion
自定义文件解析对象
@Bean(name = "multipartResolver")
public MultipartResolver multipartResolver() {
CommonsMultipartResolver resolver = new CommonsMultipartResolver();
resolver.setDefaultEncoding("UTF-8");
return resolver;
}
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~