'Uploading files Kotlin Spring Boot
So, I am trying to make and upload file(s) functionality, from some blog posts and stackoverflow questions I got this solution:
@PostMapping("/file/upload")
fun handleFileUpload(
@RequestParam("files") files: List<MultipartFile>?,
): String {
if(files == null) {
return "File is null"
}
// SOME LOGIC
return "All Good it seems"
}
But when I send request trough postman I my files are null, here is postman request:
I saw some some solutions that use @RequestPart
instead of @RequestParam
, but when I go down that path, I get unsupported media type
response.
PS: I use Java 11 and Spring Boot 2.6
UPDATE: Applied suggestions from comments and ended up with this code:
@PostMapping("/file/upload", consumes = [MediaType.MULTIPART_FORM_DATA_VALUE])
fun handleFileUpload(
@RequestPart("files") files: List<MultipartFile>?,
): String {
//SOME CODE
}
When I send request trough postman I get 415 Unsupported Media Type
Solution 1:[1]
You should use @RequestPart List<MultipartFile>
and directly specify Content-Type in Postman
Postman screenshot
Solution 2:[2]
Adding to Revasha's response, you should also add
@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
on your endpoint to avoid the 415
http error
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Revasha |
Solution 2 | T. Aris |