Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC, Upload file with other fields

I'm trying to construct method for uploading file with some other form fields.

This is standard Html form with file and some other fields:

<form action="products" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="text" name="name">
    <input type="text" name="email">
    <input type="submit" value="Upload" name="submit">
</form>

Please note: I want to use standard HTML form, not Spring form tags like <form:form ...> etc

And this is my controller method:

@ResponseBody
public MyDto createProduct(@RequestBody MyDto dto, @RequestParam MultipartFile file) {

}

But I'm getting error: Required request body content is missing.

How should I construct my web method to receive file as well as DTO object as arguments? Also it will be nice if I can have MultipartFile object included into MyDto.

like image 305
WelcomeTo Avatar asked Mar 31 '15 13:03

WelcomeTo


People also ask

How do you upload an image or file along with the post JSON data Spring Boot?

To pass the Json and Multipart in the POST method we need to mention our content type in the consume part. And we need to pass the given parameter as User and Multipart file. Here, make sure we can pass only String + file not POJO + file. Then convert the String to Json using ObjectMapper in Service layer.

How would you handle the situation where a user uploads a very large file through a form in your Spring MVC application?

A new attribute "maxSwallowSize" is the key to deal this situation. It should happen when you upload a file which is larger than 2M. Because the 2M is the default value of this new attribute .


1 Answers

Your issues occurs cause your body is consumed when binding the values of the first argument, by ommiting the annotation for the dto the framework will instantiated and populate the matching properties from the request values

  @ResponseBody
  public MyDto createProduct(MyDto dto, @RequestParam MultipartFile file) {

  }

note also that you can add a file property of the type MultipartFile to your MyDto instance, it will instantiate and bind correctly as well, so just

@ResponseBody
public MyDto createProduct(MyDto dto) {

}
like image 195
Master Slave Avatar answered Sep 27 '22 22:09

Master Slave