Spring MVC文件上传将NULL传递给控制器



我已经有一个Spring MVC应用程序,当我尝试上传多部分文件时, null 值将传递给控制器。正确传递了所有其他文本参数,只有文件输入以null的速度传递。我已经在项目中包括了多Arteresolver Bean和commons-io加上commons-fileupload依赖项。我已经检查了它是在浏览器的请求中通过的,但是它在模型中没有绑定。

这是我视图的摘要代码

<form:form method="post" enctype="multipart/form-data" action="${pageContext.request.contextPath}/profile/secure/saveIdentity" commandName="profileModel">
    <span><b>Upload your passport photo</b></span>
    <form:input  path="passportPhotograph" type="file"  id="passportPhoto"/> 
</form:form>

这是我的控制器方法的摘要

@RequestMapping(value = "/secure/saveIdentity", method = RequestMethod.POST)
public ModelAndView saveIdentity(@ModelAttribute("profileModel") @Valid ProfileModel profileModel,HttpServletRequest request){
    MultipartFile photo = profileModel.getPassportPhotograph();
    if(photo != null){ do something.... }
}

这是我的profileModel.java类摘要

public class ProfileModel{
    private MultipartFile passportPhotograph;
    public MultipartFile getPassportPhotograph() {
        return passportPhotograph;
    }
    public void setPassportPhotograph(MultipartFile passportPhotograph) {
        this.passportPhotograph = passportPhotograph;
    }
    ............
}

,在我的调度员 - 服务文件中,我已声明为多ARSOLTRESOLVER BEAN:

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="99999999999"/>
</bean>

最后在我的build.gradle文件中我添加了这些依赖项

compile('commons-io:commons-io:2.0.1')
compile('commons-fileupload:commons-fileupload:1.3.1')

之后,即使它包含在HttpservletRequest中,它也将其传递给了我的控制器。我该怎么办来解决这个问题。预先感谢您的帮助。

您需要使用@RequestMapping(value = "/secure/saveIdentity", method = RequestMethod.POST, headers = ("content-type=multipart/*"), produces = "application/json", consumes = "image/*")

通过使用带有Spring Web框架的标准服务,解决了我的问题。但是您必须使用Servlet版本3.0 才能工作。

此示例代码。点是模型中的输入标签名称绑定文件。也许您需要库JSON和文件。Ex(Commons-io,Commons-Fileupload和Gson,Gson用于在控制器中解析。

html

<form:form method="post" enctype="multipart/form-data" action="${pageContext.request.contextPath}/profile/secure/saveIdentity">
    <span><b>Upload your passport photo</b></span>
    <form:input type="file"  name="file"/> 
</form:form>

控制器

@RequestMapping(value = "test", method = RequestMethod.POST)
public String testFormData(FileAndContentModel model) {
   // break point and check model.
   return "success";
}

模型

public class FileAndContentModel {
    private MultipartFile file;
    public FileAndContentModel () {
    }
     // getter, setter

}

这不是解决方案,我只是在这里输入,因为比注释更容易阅读。请尝试最低要求,只需上传文件并验证是否有效。

表格:

<form:form method="post" enctype="multipart/form-data" action="${pageContext.request.contextPath}/profile/secure/saveIdentity">
    <span><b>Upload your passport photo</b></span>
    <input  name="file" type="file"  id="passportPhoto"/> 
</form:form>

控制器:

@RequestMapping(value = "/secure/saveIdentity", method = RequestMethod.POST)
public void saveIdentity(@RequestParam("file") MultipartFile file) {
    //please verify here if the file is null

最新更新