Spring MVC, Upload file with other fields

2019-03-15 20:09发布

问题:

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.

回答1:

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) {

}