There is a DTO :

 public class OwnerProfileUpdateDTO { private String firstName; private String lastName; private String phone; private String company; private long countryId; private long regionId; private long townId; private MultipartFile avatar; public OwnerProfileUpdateDTO() {} // getters and setters } 

There is a REST controller:

 @RestController @Secured("OWNER") @PreAuthorize("isAuthenticated()") @RequestMapping(value = "/api/v1/owner",produces = MediaType.APPLICATION_JSON_VALUE) public class ApiOwnerController { @Autowired private OwnerService ownerService; private static final Logger LOGGER = LogManager.getLogger(ApiOwnerController.class); @PostMapping(value = "/profile/update", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public Response fillUpdate(Response response, OwnerProfileUpdateDTO ownerProfileUpdateDTO) { LOGGER.info(ownerProfileUpdateDTO); response.setSuccess("OK"); return response; } } 

I send data to the server in FormData format using AJAX :

 $.ajax({ url: 'update', data: new FormData($('form')[0]), type: 'POST', dataType: 'json', processData: false, contentType: false, enctype: 'multipart/form-data' }) 

I need to transfer the file and additional data, therefore I use FormData But in ownerProfileUpdateDTO all fields are all null . why is that? I can not understand.

I tried to OwnerProfileUpdateDTO ownerProfileUpdateDTO annotation to the @RequestBody , but I OwnerProfileUpdateDTO ownerProfileUpdateDTO at the request:

 org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'multipart/form-data;boundary=----WebKitFormBoundary0iIfmbRKA2DP0lnF;charset=UTF-8' not supported 

what's wrong? how to do?

  • It turns out that the json object is transmitted, of which the file is a part? - Maksat Orunkhanov
  • @ MaksatOrunkhanov is not json . Data is transmitted in multipart/form-data format, and the server maps all parameters to my object. If you look at the request in the browser inspector on the Network tab, you will see in which format the data is transmitted. - Tsyklop

1 answer 1

In my case, everything turned out to be like this:

Added by:

 <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency> 

and this:

 @Bean(name = "multipartResolver") public CommonsMultipartResolver multipartResolver() { CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); multipartResolver.setMaxUploadSize(100000); return multipartResolver; } 

Well, in the controller itself, added @ModelAttribute :

  @PostMapping(value = "/profile/update", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public Response fillUpdate(Response response, @ModelAttribute OwnerProfileUpdateDTO ownerProfileUpdateDTO) { LOGGER.info(ownerProfileUpdateDTO); response.setSuccess("OK"); return response; }