You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot表单上传文件失败:必填参数'file'缺失求助

排查文件上传接口返回400 "Required part 'file' is not present"问题

一、Controller接口参数校验

  • 确保接口方法的文件参数注解里的名称和form-data的key完全一致,大小写敏感。比如用@RequestParam("file") MultipartFile file,那form-data里的key必须是file,不能是File或其他变体。
  • 确认接口方法标注了正确的请求类型和消费类型:
    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<String> upload(@RequestParam("file") MultipartFile file) {
        // 业务逻辑
    }
    
    没指定consumes可能导致Spring无法正确解析multipart请求。

二、Postman及curl请求校验

  • 检查Postman的form-data配置:Key必须是file,Type选File,且已正确选择本地文件,Key名称前后不能有空格或特殊字符。
  • 看Postman生成的curl命令,确认-F参数里的字段名是file=@文件路径,比如正确格式:
    curl --location --request POST 'http://localhost:8080/api/upload' \
    --form 'file=@"/Users/xxx/test.txt"'
    
    如果curl里的字段名不是file,直接修改Postman的Key即可。

三、Spring配置校验

  • 检查项目的文件上传配置,Spring Boot默认自动配置,但如果自定义了MultipartResolver,要确保配置正确:
    @Bean
    public MultipartResolver multipartResolver() {
        CommonsMultipartResolver resolver = new CommonsMultipartResolver();
        resolver.setMaxUploadSize(10 * 1024 * 1024); // 10MB
        return resolver;
    }
    
  • 查看application.properties/application.yml,确保文件上传功能开启:
    spring.servlet.multipart.enabled=true
    spring.servlet.multipart.max-file-size=10MB
    spring.servlet.multipart.max-request-size=10MB
    
    如果enabled为false,直接导致无法处理multipart请求。

四、代码链路检查

  • 确认Service层接收参数时没有错误,比如是否误将MultipartFile参数替换成了其他类型,或者传递过程中丢失了参数。
  • 如果接口有多个form字段,要确保所有字段的key都正确,没有和file冲突的配置。

内容的提问来源于stack exchange,提问作者gavi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 19:12:31