swagger-ui提交含json和multipart请求返回415 Unsupported Media Type问题
问题根因
415 Unsupported Media Type错误的核心原因是:@RequestPart注解接收自定义POJO对象时,Spring需要该multipart分段的Content-Type为application/json才能完成反序列化,但Swagger UI默认生成请求时,JSON对象对应的分段没有指定媒体类型,默认使用text/plain,Spring无法识别该类型完成反序列化,因此抛出异常。
你可以手动修改生成的curl命令验证,将certificate参数修改为-F "certificate={\"timestamp\": \"2021-11-02T22:34:03.187Z\", \"title\": \"title\" };type=application/json",请求即可正常响应。
永久解决方案
场景1:使用SpringDoc OpenAPI(Swagger 3,推荐)
在Certificate参数上添加@Parameter注解显式指定媒体类型:
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import org.springframework.http.MediaType; @RequestMapping(value = "/upload", method = RequestMethod.POST, consumes = { "multipart/form-data" }) public ResponseEntity<Certificate> create( @RequestPart("id") Long id, @RequestPart("file") MultipartFile file, @RequestPart("certificate") @Parameter(content = @Content( mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = Certificate.class) )) Certificate certificate ) { //业务代码 }
配置后Swagger UI生成请求时会自动给certificate分段添加application/json的媒体类型标识,请求可正常提交。
场景2:使用SpringFox Swagger 2
SpringFox已停止维护,优先建议升级到SpringDoc,如果需要继续使用,可以调整接收方式,将Certificate改为字符串接收后手动反序列化:
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.beans.factory.annotation.Autowired; @Autowired private ObjectMapper objectMapper; @RequestMapping(value = "/upload", method = RequestMethod.POST, consumes = { "multipart/form-data" }) public ResponseEntity<Certificate> create( @RequestPart("id") Long id, @RequestPart("file") MultipartFile file, @RequestPart("certificate") String certificateStr ) throws JsonProcessingException { Certificate certificate = objectMapper.readValue(certificateStr, Certificate.class); //业务代码 }
额外校验
确认Spring项目默认的MappingJackson2HttpMessageConverter没有被自定义配置覆盖,确保JSON序列化能力正常。
内容的提问来源于stack exchange,提问作者Bula
相关产品推荐
相关产品推荐

