0

I have a Spring Boot controller method that handles file uploads, and I'm trying to use the @ModelAttribute annotation to bind some fields from the request. Here's my controller method:

@PostMapping(value = "/{accountNo}/upload", consumes = "multipart/form-data") public ResponseEntity<Object> uploadDocument( @PathVariable Long accountNo, @ModelAttribute RequestDTO requestDTO, @RequestParam("file") MultipartFile file, Authentication authentication) { // ... } 

The RequestDTO class contains fields that I want to bind from the request body/form data. However, I'm encountering an issue where the requestDTO object is always null in the method.

Due to the extensive length of certain attribute values, passing DTO data through request parameters is not feasible.

Is there something I'm missing in my setup, or are there any common pitfalls when using @ModelAttribute in this context? How can I ensure that the requestDTO object is correctly populated from the request?

I have verified that the request is being sent correctly, including the required fields for RequestDTO.

The @RequestBody annotation cannot be used in conjunction with multipart/form-data.

I used swagger to send data using JSON format.

{ "accountNo": "211100001201", "kind": "hello", "name": "string", "url": "string", "location": "string", "storageStatus": "string", "actionType": "string", "value1": "string", "detail": "string" } 

Thank you for your assistance!

3
  • The instance cannot be null, the fields can be null, if that is the case there is something that youa re using that isn't in the question (like final methods or class, implementing an interface etc. etc.). Also what is the form you are sending? How are you sending. Commented Sep 25, 2023 at 6:54
  • I used swagger to send data using JSON format. Commented Sep 25, 2023 at 7:06
  • json isn't a form and thus cannot be used with @ModelAttribute. Commented Sep 25, 2023 at 7:10

1 Answer 1

0

If you state that your endpoint consumes = "multipart/form-data" then it does not expect to get JSON from your request to populate your DTO.

Add file to your RequestDTO and send request in "multipart/form-data" but not in JSON. (Content-Type header should contain multipart/form-data value : Content-Type: multipart/form-data;)

Here is the link how to upload file from swagger-ui. The rest of parameters should be in line with file.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.