I want to upload a file inside a form to a Spring Boot API endpoint.
The UI is written in React:
export function createExpense(formData) {
return
Add the consumer type to your request mapping .it should work fine.
@POST
@RequestMapping("/upload")
public ResponseEntity<Object> upload(@RequestParam("file") MultipartFile file,consumes = "multipart/form-data")
{
if (file.isEmpty()) {
return new ResponseEntity<Object>(HttpStatus.BAD_REQUEST);
} else {
//...
}
}
You have to tell spring you're consuming multipart/form-data
by adding consumes = "multipart/form-data"
to the RequestMapping
annotation. Also remove the RequestBody
annotation from the expenseDto
parameter.
@RequestMapping(path = "/{groupId}", consumes = "multipart/form-data", method = RequestMethod.POST)
public ExpenseSnippetGetDto create(ExpensePostDto expenseDto,
@PathVariable long groupId, Principal principal, BindingResult result)
throws IOException {
//..
}
With the posted ExpensePostDto
the title
in the request is ignored.
Edit
You'll also need to change the content type to multipart/form-data
. Sounds like that's the default for post
based on some other answers. Just to be safe, I would specify it:
'Content-Type': 'multipart/form-data'