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
.
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.
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 .
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) {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With