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

Spring Boot Multipart接口接收application/json参数及Swagger适配问题

问题解答

一、Postman自动识别功能作用

Postman的form-data参数自动识别逻辑是基于参数值的类型匹配对应Content-Type:

  • 若参数值为文件类型,会自动识别为对应文件的MIME类型,比如png文件会识别为image/png,pdf文件会识别为application/pdf
  • 若参数值为纯文本,自动识别逻辑不会主动给该part添加Content-Type请求头,Spring MVC默认会将无Content-Type的multipart part识别为application/octet-stream(二进制流),和你接口需要的JSON类型不匹配,因此抛出HttpMediaTypeNotSupportedException异常。

二、Swagger接口调用解决方案

核心思路是通过注解显式指定student这个part的媒体类型为application/json,Swagger会根据注解自动生成符合要求的请求:

1. SpringDoc OpenAPI 3(当前主流版本)

给@RequestPart参数添加@Parameter注解,指定content的媒体类型:

@RestController
@RequestMapping("/api")
public class StudentServiceController {

    @PostMapping(value = "/students", consumes = { MediaType.MULTIPART_FORM_DATA_VALUE })
    public ResponseEntity<String> storeStudent(
        @Parameter(content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE))
        @RequestPart("student") Student student
    ) {
        System.out.println(student);
        return new ResponseEntity<>("Student stored", HttpStatus.OK);
    }

}

添加注解后Swagger生成的curl命令会自动给student参数加;type=application/json后缀,最终请求符合后端要求,调用即可成功。

2. 旧版Swagger2(SpringFox)

使用@ApiImplicitParam注解指定参数的contentType:

@RestController
@RequestMapping("/api")
@Api(tags = "学生管理接口")
public class StudentServiceController {

    @ApiImplicitParam(
        name = "student",
        value = "学生信息JSON",
        required = true,
        dataType = "Student",
        paramType = "form",
        contentType = MediaType.APPLICATION_JSON_VALUE
    )
    @PostMapping(value = "/students", consumes = { MediaType.MULTIPART_FORM_DATA_VALUE })
    public ResponseEntity<String> storeStudent(@RequestPart("student") Student student) {
        System.out.println(student);
        return new ResponseEntity<>("Student stored", HttpStatus.OK);
    }

}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 11:54:00