3

Using Spring Boot 2.1.8, I have two methods in a Rest Controller that expect a single file and multiple files respectively. These are the method signatures:

@PreAuthorize("hasAnyRole('ROLE_ADMIN')") @PostMapping("/uploadMultipleFiles") public List<FileResponse> uploadMultipleFiles(@RequestParam("files") MultipartFile[] files); @PreAuthorize("hasAnyRole('ROLE_ADMIN')") @PostMapping("/upload") public FileResponse uploadFile(@RequestParam("file") MultipartFile file); 

The single upload works just perfect. I am managing to load a single file from a web client, Postman v7.25.0, and from Swagger 2.

But the multiple file method only works when uploading files from Postman, returning a 400 http error code. Therefore, it does not even enter the method.

The error message in both cases (web client or Swagger) is the same:

can't parse JSON. Raw result: Missing or unreadable multipart file in request 

This is the request headers when calling to /uploadMultipleFiles through Swagger (getting error): enter image description here

This is the request headers when calling /uploadMultipleFiles from Postman (works fine): enter image description here

This is the request headers when calling /upload from Postman (works fine): enter image description here

This is the request headers when calling /upload through Swagger (works fine): enter image description here

Firstly I thought that Content-Type might have something to do with my problem. But Swagger sends always application/json, and it works with the single upload endpoint.

Any idea?

1 Answer 1

1

When you are dealing with file uploads using multipartfile, you should set the content type of the request to multipart/form-data. The screenshot shows that Postman is using multipart/form-data and not application/json.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much for the answer. The question then is: how do I tell Swagger to set the Content-Type to multipart/form-data? And one comment: the last image shows how the single file upload works fine from swagger (setting Content-Type to application/json).
If you're using the OAS3 standard in Swagger, you can use this: swagger.io/docs/specification/describing-request-body They use application/json for their example and you can replace that with the content type on the answer. Without looking at the request body, I unfortunately can't say why it works like that with Swagger

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.