Spring MVC映射方法没有使用POST调用

时间:2014-11-02 00:59:41

标签: java spring spring-mvc

我正在尝试使用Spring MVC上传文件。 这是.jsp页面中的表单

<form:form method="post" commandName="file"  enctype="multipart/form-data">
    Upload your file please:
    <input type="file" name="file" />
    <input type="submit" value="upload" />
    <form:errors path="file" cssStyle="color: #ff0000;" />
</form:form>

在我的控制器中,我有GET和POST方法:

@RequestMapping(method = RequestMethod.GET)
public String getForm(Model model) {
    File fileModel = new File();
    model.addAttribute("file", fileModel);
    return "file";
}

@RequestMapping(method = RequestMethod.POST)
public String fileUploaded(Model model, @Validated File file, BindingResult result) {
    String returnVal = "successFile";
    logger.info("I am here!!!");
    if (result.hasErrors()) {
        returnVal = "file";
    }else{
        MultipartFile multipartFile = file.getFile();
    }
    return returnVal;
}

验证只是检查文件大小是否为零:

public void validate(Object target, Errors errors) {
    File imageFile = (File)target;
    logger.info("entered validator");
    if(imageFile.getFile().getSize()==0){
        errors.rejectValue("file", "valid.file");
    }
}

方法GET工作正常并返回文件视图,但是控制器中的POST方法不会被调用。单击上传按钮时没有任何反应。

2 个答案:

答案 0 :(得分:0)

我希望这会对你有所帮助:

控制器代码

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public String uploadInputFiles(@RequestParam("file1") MultipartFile file,
        @RequestParam("fileName") String fileName,
        @RequestParam("fileType") String fileType){

    System.out.println("Upload File Controller has been called");
}

表格提交:

<form method="POST" action="uploadFile" enctype="multipart/form-data">
    File to upload: <input type="file" name="file"><br /> 
    Name: <input type="text" name="name"><br /> <br /> 
    <input type="submit" value="Upload"> Press here to upload the file!
</form>

答案 1 :(得分:0)

我认为您的配置应该如下所示在mvc-servlet.xml文件中。

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

并更改您的帖子api,如下所示。

@RequestMapping(method = RequestMethod.POST,value = "/uploadFile")
public String fileUploaded(Model model, @RequestParam("file") MultipartFile file, BindingResult result) {
     String result = "not uploaded";
     if(!file.isEmpty()){
            MultipartFile multipartFile = file.getFile();
            //code for storing the file in server(in db or system)
      }
     else{
          result = "can not be empty;"
      }       
    return result;
}