Search code examples
javajsonspringhttpmultipartform-data

How to receive multipart request in Spring App


I've seen many sources and also few questions on SO but didn't find 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 void 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 void 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 void 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: enter image description here

enter image description here


Solution

  • Yes, I agree with Vladimir; multipart/form-data, @RequestParts instead of body & param:

    @PutMapping(value = "/{id}/update", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
    public void updateCar(@PathVariable(value = "id") Long carId,
            @RequestPart("car") Car car, 
            @RequestPart("file") MultipartFile file) {
       ...
    

    Then in Postman:

    Postman Screenshot

    • use Body>form-data
    • when issues:
      • display Content-Type column.
      • set Content-Type per part.