Spring MVC,与其他字段上传文件 [英] Spring MVC, Upload file with other fields

查看:585
本文介绍了Spring MVC,与其他字段上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在试图构建上传带有其他表单字段的文件的方法。

这是带有文件和其他字段的标准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 ...> 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.

解决方案

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,与其他字段上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆