[英]Spring MVC mapped method not being called using POST
我正在尝试使用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方法。 单击上传按钮没有任何反应。
我希望这能帮到您:
控制器代码
@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>
我认为您的配置应类似于下面的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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.