spring-boot - [SWAGGER 2 UI]:启用多部分/表单数据请求
问题描述
我有一个简单的控制器方法,可以捕获一些JSON
信息以及任意数量的上传图像文件:
@PostMapping(value = "/products", consumes = MediaType.MULTIPART_FORM_DATA_VALUE )
public ResponseEntity<ResponseMessage> postProduct(@RequestPart(name = "request") final MyJsonBody postRequest,
@RequestPart(name = "images") final ist<MultipartFile> images)
{
log.info("Request id and name fields: " + postRequest.getProductId() + ", " + postRequest.getProductName() + ".");
log.info("Received a total of: " + images.size() + " files.");
return success("Just wanted to test the upload functionality!", null, HttpStatus.OK); // A private method I have to return an appropriate ResponseEntity<> to the user.
}
该类MyJsonBody
是一个用于测试目的的简单 POJO:
@Data
@Builder(access = PUBLIC)
@AllArgsConstructor
@NoArgsConstructor
public class MyJsonBody
{
@JsonProperty("id") private String productId;
@JsonProperty("name") private String productName;
}
使用 Postman 时,我的示例 multipart/form-data POST 请求工作得很好:
正如您在此处看到的,Springboot 完全可以处理请求并按预期打印数据:
2020-12-21 14:28:20.321 INFO 11176 --- [nio-8080-exec-3] c.j.r.fileuploads.FileUploadController : Request id and name fields: RANDOM_ID, null.
2020-12-21 14:28:20.321 INFO 11176 --- [nio-8080-exec-3] c.j.r.fileuploads.FileUploadController : Received a total of: 2 files.
我的团队使用 Swagger 2,能够使用 Swagger UI 调试 API 对我来说很重要。不幸的是,当从 UI 发送相同的请求时:
UI 似乎没有将请求作为multipart/form-data
请求发送,而是作为application/octet-stream
请求发送:
2020-12-21 14:27:40.095 WARN 11176 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/octet-stream' not supported]
Web 上的大多数信息都涉及 OpenAPI 规范版本 3,但我们目前使用的是 2.8 版本。关于我如何使请求畸形的任何想法?
编辑:以下是我的 Swagger 配置类。我在这个玩具项目中的所有代码都在 package 下com.jason.rest.fileuploads
。
@Configuration
@EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurationSupport {
@Bean
public Docket productApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select().apis(RequestHandlerSelectors.basePackage("com.jason.rest.fileuploads"))
.paths(PathSelectors.any())
.build();
}
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
@Bean
public LinkDiscoverers discoverers() {
List<LinkDiscoverer> plugins = new ArrayList<>();
plugins.add(new CollectionJsonLinkDiscoverer());
return new LinkDiscoverers(SimplePluginRegistry.create(plugins));
}
}
解决方案
推荐阅读
- python - Python - 使用安全添加功能进行多处理
- python - 如何为 json.load 设置正确的编码
- java - 连接到 ec2-linux 实例后 Hive 未连接
- php - PHP套接字服务器如何接受与多个客户端的连接和通信(android)
- python - 如何使用 TFSlim 库训练模型?
- sql - 如何在 2 个不同的年份和 2 个不同的季度之间选择年份和季度?
- python - Python 3.4.4 应用程序工作,但 exe 失败,出现 utf-8 错误
- java - Java 12 中缺少集成测试阶段
- amazon-web-services - Google Domains 中的域和 Amazon S3 中的代码
- python - 通过继承函数处理后的类型变化