I've seen many sources and also few questions on SO but didn't found solution.
I want to send to my Spring app POST/PUT-requests that contain JSON-object Car
and attached file.
For the moment I have a CarController
which correctly works with JSON-objects
@PutMapping("/{id}/update")
public updateCar(@PathVariable(value = "id") Long carId, @Validated @RequestBody Car car) throws ResourceNotFoundException {
// I can work with received car
}
I also have a FileController
which correctly works with file
@PostMapping("/upload")
public uploadFiles(@RequestParam("file") MultipartFile file) throws IOException {
// I can work with received file
}
But how should my method look like to be able to work with both car
and file
? This code doesn't provide me any of car
or file
.
@PutMapping("/{id}/update")
public updateCar(@PathVariable(value = "id") Long carId, @Validated @RequestBody Car car, @RequestParam("file") MultipartFile file) throws ResourceNotFoundException, IOException {
// can not work neither with car nor with file
}
Separate controllers work well during test from Postman. But when I try third code I got these results:
CodePudding user response:
You can use consumes = { MediaType.MULTIPART_FORM_DATA_VALUE }
field of @RequestMapping
annotation and @RequestPart
annotation for method parameters:
ResponseEntity<> foo(@RequestPart ParType value, @RequestPart MultipartFile anotherChoice) {
...
CodePudding user response:
- use Body>form-data
- when issues:
- display
Content-Type
column. - set
Content-Type
per part.
- display
CodePudding user response:
There is nothing wrong with your code and it could work as it is.
You could eventually improve its readability by using @RequestPart instead of @RequestParam and @RequestBody when it's a multipart request.
You can find more details about multipart requests in this article
Check the box "Content-Type" and the new column will appear:
And finally, define the content type of each part.