2014-11-02 86 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