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

Spring中如何通过OpenAPI让Swagger为表单部分添加application/json

解决Spring控制器混合JSON与文件参数时Swagger 415错误的OpenAPI配置方案

问题核心

控制器同时接收文件和JSON参数时,Swagger生成的请求未给JSON参数的form-data part指定application/json媒体类型,导致后端解析失败触发415错误。需通过OpenAPI配置明确标记JSON参数的媒体类型。

具体解决方案

1. 调整控制器参数注解

将JSON参数的@RequestBody替换为@RequestPart,因为form-data中的JSON属于独立请求部分,@RequestPart能正确识别并支持指定媒体类型:

@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<String> upload(
    @RequestPart("file") MultipartFile file,
    @RequestPart("exampleDto") ExampleDto exampleDto
) {
    // 业务逻辑实现
    return ResponseEntity.ok("操作成功");
}

2. 用OpenAPI注解指定JSON参数媒体类型

在@RequestPart参数上添加OpenAPI专属的@RequestPart注解(来自io.swagger.v3.oas.annotations.parameters包),通过@Content明确指定媒体类型为application/json:

@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@Operation(summary = "上传文件并提交JSON数据")
public ResponseEntity<String> upload(
    @RequestPart("file") MultipartFile file,
    @io.swagger.v3.oas.annotations.parameters.RequestPart(
        name = "exampleDto",
        content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE)
    )
    @RequestPart("exampleDto") ExampleDto exampleDto
) {
    return ResponseEntity.ok("操作成功");
}

3. 全局配置(可选)

若多个接口存在类似场景,可通过全局OpenAPI Bean统一配置form-data中JSON参数的媒体类型:

@Bean
public OpenAPI customOpenAPI() {
    return new OpenAPI()
        .components(new Components()
            .addRequestBodies("MultipartJsonRequest", new RequestBody()
                .content(new Content()
                    .addMediaType(MediaType.MULTIPART_FORM_DATA_VALUE, new MediaType()
                        .encoding(new Encoding()
                            .addProperty("exampleDto", new EncodingObject()
                                .contentType(MediaType.APPLICATION_JSON_VALUE)
                            )
                        )
                    )
                )
            )
        );
}

原@Content无效原因

之前直接使用@Content未生效,大概率是因为仍用@RequestBody标记JSON参数,Swagger无法将其识别为form-data的一部分;或是@Content未关联到具体的request part参数,导致配置未被正确应用。

内容的提问来源于stack exchange,提问作者stefan.stt

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 08:53:22