我正在尝试使用 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>
在我的 Controller 中,我有 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 工作正常并返回文件 View ,但是 Controller 中的 POST 方法不会被调用。单击上传按钮时没有任何反应。
最佳答案
希望这对您有帮助:
Controller 代码
@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>
关于java - Spring MVC 映射方法未使用 POST 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26694935/