SpringBoot中的multipartResolver上传文件配置
目录
- multipartResolver上传文件配置
- 1、gradle配置
- 2、注册Bean
- SpringBoot MultipartResolver的坑
- 解决方案
multipartResolver上传文件配置 【SpringBoot中的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*1024resolver.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; }
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
推荐阅读
- 热闹中的孤独
- JS中的各种宽高度定义及其应用
- Activiti(一)SpringBoot2集成Activiti6
- 我眼中的佛系经纪人
- 《魔法科高中的劣等生》第26卷(Invasion篇)发售
- Android中的AES加密-下
- 放下心中的偶像包袱吧
- C语言字符函数中的isalnum()和iscntrl()你都知道吗
- SpringBoot调用公共模块的自定义注解失效的解决
- C语言浮点函数中的modf和fmod详解