0

I have an API for uploading multiple files with below signature - takes in a list of multipart files and a request object.

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

When I test this API using Postman it works but I when try using swagger, I noticed the content-type is passed as application/json and the API gives an error 'Current request is not multpart'. I tried adding consumes to @ApiOperation but the content-type is still application/json.

Farhan
  • 411
  • 1
  • 10
  • 23
  • 1
    Are you using Swagger 1.x with Springfox, or Swagger 2.x with Springdoc/Springfox? I see that you're using `@ApiOperation` which is from Swagger 1.x but your question has a `swagger-2.0` tag to it. Also please clarify the framework you're using. – Debargha Roy Mar 03 '21 at 17:44
  • Apologies @Debargha Roy, I am using Spring (Spring boot application) with Swagger 2 - Springfox. Also, I now see the content-type is multipart/form-data but the list of files are coming up as null – Farhan Mar 04 '21 at 13:05

1 Answers1

6

Files in OpenAPI 3.x are better represented by application/octet-stream.

I solved the issue using the below approach

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

More details for file upload in the OpenAPI 3 specification can be found here

Debargha Roy
  • 2,320
  • 1
  • 15
  • 34