2014-11-02 85 views
1

我想使用Spring MVC上传文件。 这里是.jsp页面未使用POST调用Spring MVC映射方法

<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方法不会被调用。点击上传按钮时没有任何反应。

回答

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> 
+0

感谢您的回复,但这是我的一个非常愚蠢的错误。我没有在我的jsp – 2014-11-04 01:49:19

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; 
} 
+0

中包含'<%@ taglib uri =“http://www.springframework.org/tags/form”prefix =“form”%>'谢谢你的回复,我确实改变了我的帖子api,但这是我的一个非常愚蠢的错误。我没有在我的jsp中加入<%@ taglib uri =“http://www.springframework.org/tags/form”prefix =“form”%>' – 2014-11-04 01:50:14