Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multipart Request with MultipartFile as Optional Field - Spring MVC

I am using Spring MVC on a J2EE Web application.
I have created a method that bounds the request body to a model like the above

@RequestMapping(value = "/", method = RequestMethod.POST, produces = "application/json")
public AModel createEntity(@Valid @ModelAttribute MyInsertForm myInsertForm) {
    // coding..
}  

Everything are working great and when i include a property of type MultipartFile in the MyEntityForm, then i have to make the request with content type "multipart/form-data".
Also, everything are working great with this scenario too.

The problem i am facing is that i would like to have the MultipartFile property as optional.
When a client request include a file my method works great but when a client request does not include a file spring throws a

HTTP Status 500 - Request processing failed; nested exception is org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; nested exception is org.apache.commons.fileupload.FileUploadException: Stream ended unexpectedly

Is there any way to solve this issue without creating two methods on my controller (one with a MultipartFile and another without)?

like image 299
Georgios Syngouroglou Avatar asked Jul 14 '14 21:07

Georgios Syngouroglou


People also ask

Can we use multipart and @RequestBody together in spring?

Usually we add @RequestBody and mention the Class name for creating a data using POST method. But here, we should add both Json and multipart both. So, annotation should be altered.

How do I pass a MultipartFile in RestTemplate?

Set the content-type header value to MediaType. MULTIPART_FORM_DATA. When this header is set, RestTemplate automatically marshals the file data along with some metadata. Next, build the request body as an instance of LinkedMultiValueMap class.

What is MultipartFile used for?

Interface MultipartFile. A representation of an uploaded file received in a multipart request. The file contents are either stored in memory or temporarily on disk. In either case, the user is responsible for copying file contents to a session-level or persistent store as and if desired.


2 Answers

I had the same issue and just adding the required=false worked for me; because, I don't send a file all the time. Please find the sample code below,

@RequestMapping(value = "/", method = RequestMethod.POST, produces = "application/json")
public AModel createEntity(@Valid @ModelAttribute MyInsertForm myInsertForm, @RequestParam(value ="file", required=false) MultipartFile file) {
    // coding..
}  
like image 116
tk_ Avatar answered Sep 21 '22 19:09

tk_


Give a try by adding

(required=false)

to multipart property in method signature.

like image 45
Juned Ahsan Avatar answered Sep 23 '22 19:09

Juned Ahsan