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

REST API中HttpMediaTypeNotSupportedException异常排查求助

问题原因

你遇到的异常核心原因是**@RequestBody注解不能用于multipart/form-data类型的请求**:

  • @RequestBody的作用是将HTTP请求体(通常是JSON/XML格式)直接绑定到DTO对象,但multipart/form-data请求由多个部分组成(文件+普通表单字段),Spring无法用@RequestBody的解析逻辑处理这种请求格式,因此会抛出HttpMediaTypeNotSupportedException。
  • 虽然文件参数能正常处理,但异常是因为Spring先尝试解析@RequestBody对应的DTO失败导致的,后续文件处理流程仍能执行,所以出现了"请求正常但日志抛异常"的矛盾现象。
解决方法

修改接口方法的参数绑定方式,移除@RequestBody,改用@ModelAttribute(或者省略,Spring会自动处理)来绑定普通表单字段:

@PostMapping(produces = MediaType.APPLICATION_JSON_VALUE,consumes = MediaType.MULTIPART_FORM_DATA_VALUE,value = "/{userId}")
@Override
public ResponseEntity<WarrantyDetailsRequestResponse> createWarrantyDetails
        (@ModelAttribute UsersWarrantyDetailsDTO usersWarrantyDetails,
         @PathVariable("userId") Long userId,
         @RequestParam("qrCodeImage") MultipartFile qrCodeImage,
         @RequestParam("productInvoice") MultipartFile productInvoice,
         @RequestParam("other_files") MultipartFile[] otherProductFiles) {
    return new ResponseEntity<>(warrantyDetailsRequestResponse, HttpStatus.CREATED);
}

或者直接省略@ModelAttribute,Spring会自动将multipart表单中的普通字段映射到DTO对象:

@PostMapping(produces = MediaType.APPLICATION_JSON_VALUE,consumes = MediaType.MULTIPART_FORM_DATA_VALUE,value = "/{userId}")
@Override
public ResponseEntity<WarrantyDetailsRequestResponse> createWarrantyDetails
        (UsersWarrantyDetailsDTO usersWarrantyDetails,
         @PathVariable("userId") Long userId,
         @RequestParam("qrCodeImage") MultipartFile qrCodeImage,
         @RequestParam("productInvoice") MultipartFile productInvoice,
         @RequestParam("other_files") MultipartFile[] otherProductFiles) {
    return new ResponseEntity<>(warrantyDetailsRequestResponse, HttpStatus.CREATED);
}

同时要确保Postman发送请求时,普通字段是作为form-data的键值对发送的,而不是放在JSON请求体里。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 11:29:55