0

我有一个用于上传具有以下签名的多个文件的 API - 包含一个多部分文件列表和一个请求对象。

@ApiOperation(consumes=MediaType.MULTIPART_FORM_DATA_VALUE)
@PostMapping("/upload")
public void uploadMultipleFiles(@RequestParam("req") RequestDTO request, @RequestParam("files") List<MultipartFile> files) {}

当我使用 Postman 测试这个 API 时,它可以工作,但是当我尝试使用 swagger 时,我注意到内容类型作为 application/json 传递,并且 API 给出错误“当前请求不是 multpart”。我尝试向@ApiOperation 添加消耗,但内容类型仍然是应用程序/json。

4

1 回答 1

3

OpenAPI 3.x 中的文件最好用application/octet-stream.

我使用以下方法解决了这个问题

@Operation(  // Swagger/OpenAPI 3.x annotation to describe the endpoint
    summary = "Small summary of the end-point",
    description = "A detailed description of the end-point"
) 
@PostMapping(
    value = "/uploads", 
    consumes = {MediaType.MULTIPART_FORM_DATA_VALUE}  // Note the consumes in the mapping
)  
public void uploadMultipleFiles (

    // ------------ Multipart Object ------------

    @Parameter(description = "Additional request data")  // Swagger/OpenAPI annotation
    @RequestParam("req") RequestDTO request,             // Spring annotation

    // ------------ File uploads go next ------------

    @Parameter(
        description = "Files to be uploaded", 
        content = @Content(mediaType = MediaType.APPLICATION_OCTET_STREAM_VALUE)  // Won't work without OCTET_STREAM as the mediaType.
    )
    @RequestParam("files") List<MultipartFile> files  // Spring annotation
)

有关 OpenAPI 3 规范中文件上传的更多详细信息,请参见此处

于 2021-03-04T18:08:06.870 回答