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

Spring Boot 3.1.4中@RequestPart MultipartFile接口调用报错求助

Spring Boot文件上传接口400 Bad Request排查方案

一、确认请求格式合规

调用接口时必须满足以下要求:

  • 请求头Content-Type必须为multipart/form-data
  • 表单参数名必须与接口中@RequestPart(value = "file")的file一致
  • 正确的curl调用示例:
    curl -X POST -F "file=@/本地文件路径" http://localhost:8080/upload
    
    Postman需选择form-data类型,键名填file,值选择本地文件。

二、修正接口配置与返回值

原接口的consumes = {"*/*"}会导致Spring无法精准识别multipart请求,同时返回null可能触发框架内部处理异常,建议修改为:

import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

// 类注解省略
public class UploadController {
    private static final Logger log = LoggerFactory.getLogger(UploadController.class);

    @PostMapping(
        value = "/upload",
        consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
        produces = MediaType.APPLICATION_JSON_VALUE
    )
    public ResponseEntity<String> upload(@RequestPart(value = "file") MultipartFile file) {
        log.info("upload :: file name: {}, size: {} bytes.", file.getOriginalFilename(), file.getSize());
        return ResponseEntity.ok("文件上传成功");
    }
}

三、配置Multipart参数(可选)

若存在文件大小超限问题,可在application.properties中添加配置:

# 单个文件最大允许大小
spring.servlet.multipart.max-file-size=10MB
# 单次请求总文件大小上限
spring.servlet.multipart.max-request-size=10MB
# 开启Multipart支持(默认已开启)
spring.servlet.multipart.enabled=true

四、查看详细错误日志

默认错误信息过于简略,开启DEBUG日志定位具体问题:
在application.properties中添加:

logging.level.org.springframework.web=DEBUG
logging.level.org.springframework.web.multipart=DEBUG

重新调用接口后,控制台会输出具体错误原因(如参数缺失、请求体解析失败等)。

五、排查拦截器/过滤器干扰

若项目存在自定义拦截器或过滤器,需确保它们不会提前读取或修改multipart/form-data类型的请求体,否则会导致Spring无法正确解析文件参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 05:22:12