Spring MVC - Multipart表单数据

时间:2015-10-15 09:17:55

标签: java spring jsp spring-mvc multipartform-data

我收到了这个jsp文件:

<form:form class="main-section" modelAttribute="demandeForm" commandName="demandeForm" 
name="demandeForm" method="post" enctype="multipart/form-data;charset=UTF-8" action="/validate.do?valider=valider">

<!-- Some input text -->

<ul>
   <li>
      <input type="file" name="file" >
   </li>
   <li>
      <input type="file" name="file" >
   </li>
   <li>
      <input type="file" name="file" >
   </li>
</ul>

这是我的表单类:

public class DemandeForm {

    private MultipartFile[] file;

    public MultipartFile[] getFile() {
        return file;
    }

    public void setFile(final MultipartFile[] pFile) {
        this.file = pFile;
    }
}

我的控制员:

@RequestMapping(method = RequestMethod.POST, params = "valider")
public String valider(@Valid final DemandeForm pForm, final BindingResult pResult, final Model pModel, final HttpServletRequest pRequest) {

    // do things

    if (pResult.hasErrors()) {
        return MY_VUE;
    }

    // do things

}

pResult有绑定错误,这是错误:

Failed to convert property value of type java.lang.String[] 
to required type org.springframework.web.multipart.MultipartFile[] 
for property file; nested exception is java.lang.IllegalStateException: 
Cannot convert value of type [java.lang.String] to required type 
[org.springframework.web.multipart.MultipartFile] for property file[0]: 
no matching editors or conversion strategy found 

自从我在enctype值上添加charse=UTF-8后出现错误。我需要这个,因为我有这个重音和UTF-8字符的文件。

我该如何处理?

2 个答案:

答案 0 :(得分:1)

您尝试过:

<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  <property name="defaultEncoding"><value>utf-8</value></property>
</bean>

不要使用:

enctype="multipart/form-data;charset=UTF-8"

在您的表单中

答案 1 :(得分:0)

您可以将控制器参数设置为

@RequestParam("file") MultipartFile file

然后你可以得到文件名,大小等......比如

file.getOriginalFilename()