Spring Boot+Swagger UI上传文件+JSON报415错误求配置方案
解决Swagger UI上传JSON+文件时的415 Unsupported Media Type问题
问题原因
Swagger UI默认处理multipart/form-data请求时,会把JSON对象类型的参数拆分成表单字段,不会为该参数设置application/json的Content-Type,导致后端无法正确解析PersonDTO,从而抛出415错误。Postman中手动指定了Content-Type,所以能正常运行。
可行解决方案
方案1:给参数添加注解明确媒体类型与渲染方式
直接在接口的PersonDTO参数上添加注解,既指定该部分的媒体类型,又让Swagger UI渲染为JSON文本域:
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 io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public ResponseEntity<String> upload( @Parameter(content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE)) @Schema(type = "string", format = "json") @RequestPart("person") PersonDTO person, @RequestPart("file") MultipartFile file ) { // 你的业务逻辑实现 return ResponseEntity.ok("上传成功"); }
@Parameter(content = @Content(mediaType = ...)):告诉Swagger UI发送请求时,给person部分设置application/json的Content-Type@Schema(type = "string", format = "json"):让Swagger UI把该字段渲染成可编辑的JSON文本域,而非拆分的表单字段
方案2:全局配置Schema(多接口复用场景)
如果多个接口都需要处理类似的JSON+文件上传,可以全局定义PersonDTO的Swagger Schema:
import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.components.Components; import io.swagger.v3.oas.models.media.Schema; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class OpenApiConfig { @Bean public OpenAPI customOpenAPI() { return new OpenAPI() .components(new Components() .addSchemas("PersonDTO", new Schema<>() .type("string") .format("json"))); } }
之后在接口参数上只需添加@Parameter(content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE))即可,同样能实现文本域渲染和正确的Content-Type设置。
注意事项
- 确保PersonDTO类具备无参构造函数,且字段的getter/setter齐全,保证Jackson能正常序列化/反序列化
- 必须使用
@RequestPart而非@RequestParam来接收multipart请求中的复杂类型参数,@RequestPart专门用于处理multipart请求的各个部分,支持复杂对象解析
配置完成后,在Swagger UI中person字段会显示为JSON文本域,输入符合PersonDTO格式的JSON内容,选择文件后发送请求即可正常调用接口,不再出现415错误。
内容的提问来源于stack exchange,提问作者blaiso
相关产品推荐
相关产品推荐

