首页 > 解决方案 > [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 发送相同的请求时:

Swagger 请求结构

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));

    }

}

标签: spring-bootmultipartform-dataswagger-uiswagger-2.0

解决方案


推荐阅读