我有一个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给出一个错误"Current request is not multpart"。我尝试将consumps添加到@ApiOperation,但内容类型仍然是application/json。
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规范中文件上传的更多详细信息可以在这里找到