Spring Boot 3.1.4中@RequestPart MultipartFile接口调用报错求助
Spring Boot文件上传接口400 Bad Request排查方案
一、确认请求格式合规
调用接口时必须满足以下要求:
- 请求头
Content-Type必须为multipart/form-data - 表单参数名必须与接口中
@RequestPart(value = "file")的file一致 - 正确的curl调用示例:
Postman需选择curl -X POST -F "file=@/本地文件路径" http://localhost:8080/uploadform-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
相关产品推荐
相关产品推荐

