2

I want to receive multi-part image file with request body data, but could not able to figure it out, why it is throwing org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/octet-stream' not supported exception

Below is my implementation

public ResponseEntity<GlobalResponse> createUser(@Valid @RequestPart("json") UserDTO userDTO ,@RequestPart(value ="file", required=false)MultipartFile file) throws IOException {

      //Calling some service

      return new ResponseEntity<>( HttpStatus.OK);
}

EDIT: This is my postman configuration

enter image description here

camelCode
  • 243
  • 3
  • 16

2 Answers2

2

Since you're sending data in form-data which can send data in key-value pairs. Not in RequestBody so you need to modify your endpoint like this:

@PostMapping(value = "/createUser")
public ResponseEntity createUser(@RequestParam("json") String json, @RequestParam("file") MultipartFile file) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    UserDTO userDTO = objectMapper.readValue(json, UserDTO.class);
    // Do something
    return new ResponseEntity<>(HttpStatus.OK);
}

You need to receive your UserDTO object in String representation and then map it to UserDTO using ObjectMapper. This will allow you to receive MultipartFile and UserDTO using form-data.

Mushif Ali Nawaz
  • 3,707
  • 3
  • 18
  • 31
0

As per your exception: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/octet-stream' the method is not expecting a multipart data so,

Specify request to consume MultiPart data in @RequestMapping configuration:

@Postmapping("/api/v1/user", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) 
public ResponseEntity<GlobalResponse> createUser(@Valid @RequestPart("json") UserDTO userDTO ,@RequestPart(value ="file", required=false)MultipartFile file) throws IOException {

      //Calling some service

      return new ResponseEntity<>( HttpStatus.OK);
}
Mustahsan
  • 3,852
  • 1
  • 18
  • 34