原创

Spring boot MultipartResolver

目录

  1. StandardServletMultipartResolver
  2. CommonsMultipartResolver
    2.1 排除默认配置
    2.2 添加 CommonsMultipartResolver 的依赖
    2.3 创建文件解析对象

实现了 MultipartResolver 常用接口有两个:

  一个是 CommonsMultipartResolver:使用Jakarta Commons FileUpload 解析 multipart 请求;

  一个是 StandardServletMultipartResolver:依赖于 Servlet 3.0 解析 multipart 请求;

  1. StandardServletMultipartResolver
      Spring boot 默认使用 StandardServletMultipartResolver 解析 multipart 请求;
@Configuration
@ConditionalOnClass({ Servlet.class, StandardServletMultipartResolver.class,
        MultipartConfigElement.class })
@ConditionalOnProperty(prefix = "spring.servlet.multipart", name = "enabled", matchIfMissing = true)
@ConditionalOnWebApplication(type = Type.SERVLET)
@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;
    }

}

2. CommonsMultipartResolver
2.1 排除默认配置

spring:
  autoconfigure:
    exclude: org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration

2.3 创建文件解析对象

@Slf4j
@Configuration
public class  WebMvcConfig implements WebMvcConfigurer {

    @Bean(name = "multipartResolver")
    public MultipartResolver multipartResolver() {
        log.info("Loading the multipart resolver");
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
        return multipartResolver;
    }
}
正文到此结束
Loading...