问题描述
我正在试图构建上传带有其他表单字段的文件的方法。
这是带有文件和其他字段的标准Html表单:
< form action =productsmethod =postenctype =multipart / form-data>
< input type =filename =file>
< input type =textname =name>
< input type =textname =email>
< input type =submitvalue =Uploadname =submit>
< / form>
请注意:我想使用标准的HTML表单,而不是像< form:form ...>
etc
这是我的控制器方法:
@ResponseBody
public MyDto createProduct(@RequestBody MyDto dto,@RequestParam MultipartFile file){
}
但是我收到错误:缺少必需的请求正文内容
。
如何构建我的web方法来接收文件以及DTO对象作为参数?如果我可以将MultipartFile对象包含到 MyDto
中,那将会很不错。
您的问题发生时,会导致您的身体在绑定第一个参数的值时消耗,通过省略dto的注释将实例化并从请求值填充匹配的属性。
@ResponseBody
public MyDto createProduct(MyDto dto,@RequestParam MultipartFile file){
}
$ b还要注意,您可以添加 MultipartFile 类型的文件属性到您的 MyDto 实例,它将实例化并正确绑定,所以只需
@ResponseBody
public MyDto createProduct(MyDto dto){
}
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 ...>
etcAnd 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
.解决方案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) { }
这篇关于Spring MVC,与其他字段上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!