Springboot的文件上传接口,使用postman测试一直报Required request part 'file' is not present错误

最近在写一个springboot的文件上传接口,根据从网上找到的知识点,我很快写好了一个上传接口,接口内容如下:

Springboot的文件上传接口,使用postman测试一直报Required request part 'file' is not present错误

 

和别人的接口基本一致,并且我也按照网上查找的方式,采用postman方式来上传文件,如下图所示

Springboot的文件上传接口,使用postman测试一直报Required request part 'file' is not present错误

问题来了,我每次提交测试,都会报Required request part 'file' is not present异常,从网上找到的绝大部分答案,都是要么上传文件的key不是file啦,要么就是什么headers配置的不正确啦,或者在application.properties内配置spring.http.multipart.enabled=true

然而无论我怎么修改怎么配置,都不正确,实在是崩溃,以为是自己运气差,或者什么spring或者postman版本的问题,导致文件上传功能有哪些我想不到的问题!

在连续头疼了两天之后,终于在一次无意中的搜索中,找到了一个新方向,那篇文件地址如下:

https://www.jianshu.com/p/757c60eeb58d

这片文章给了一个新的思路,就是在排除一般参数问题的基础之上,还有可能是你本身springboot进行文件解析的multipartResolver可能不正确,在解析上应该采用CommonsMultipartResolver,我整理了那片文章之后,自己搜索了相关的配置范畴,进行了自己本地化的配置方式,如下所示:

1,pom.xml内添加新的依赖

<dependency>
   <groupId>commons-fileupload</groupId>
   <artifactId>commons-fileupload</artifactId>
   <version>1.4</version>
</dependency>

2,application.properties内添加配置

#排除默认配置
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration

3,添加Bean注入--这里面如果有额外的@Override,无需关心,直接空置即可

public class WebMvcConfig implements WebMvcConfigurer {

    private static final Log log = LogFactory.getLog(WebMvcConfig.class);

    @Bean(name = "multipartResolver")
    public MultipartResolver multipartResolver() {
        log.info("Loading the multipart resolver");
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
        return multipartResolver;
    }
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {

    }

   @Override
   public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {

   }

}

经过上面三个配置之后,我重新编译springboot工程,其他的都不变(包括postman),然后再次上传文件,这次文件就可以正常上传了,我的问题也终于解决了!

哦对了,我的spring的版本是1.4.2.RELEASE,可能高级别的springboot版本没有这个问题,我还未测试过,如果小伙伴们使用的springboot版本和我差不多,出现的问题也差不多,可以采用和我相似的解决方案!