更新:我观察到传递空值的原因是enctype="multipart/form-data"
,但需要该部分才能将文件传递给控制器。下面的问题仍然存在。
我一直在尝试设置一个允许用户上传文档的 Spring MVC 页面。我环顾四周,似乎对我应该如何实现这个(使用“commons-fileupload”和“commons-io”)有了一个大致的了解,所以以下是我的视图、控制器和模型。
看法:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ page session="false" %>
<html>
<head>
<title>Upload Document</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
</script>
<script type="text/javascript" src="resources/rulesextractor.js"></script>
<link rel="stylesheet" type="text/css" href="./resources/css/rulesextractor.css" />
</head>
<body>
<c:import url = "./header.jsp">
<c:param name = "title" value = "Upload Document"/>
<c:param name = "region" value = "${region}"/>
</c:import>
<br>
Please choose a Document to upload
<br>
<form:form method="POST" modelAttribute="uploadForm" commandName="uploadForm" name="uploadForm" id="uploadForm" enctype="multipart/form-data">
<form:input path="fileData" name="fileData" type="file"/>
<br>
<input type="submit" name="submit" value="Submit" id="subbtn"/>
<input type="button" value="Main Menu" onclick="back();"/>
</form:form>
</body>
</html>
控制器:
@Controller
public class UploadController extends BaseController {
private static final Logger logger = LoggerFactory.getLogger(FlowController.class);
//@Autowired
//private UserPreferences userPreferences;
@Autowired
GenericSearchBO genericSearchBO;
@RequestMapping(value = "upload", method = RequestMethod.GET)
public String getUploadPage(Model m){
logger.info("UploadController: Getting Upload page");
updateRegionOnModel(m);
m.addAttribute(new UploadForm());
return "/pages/upload";
}
@RequestMapping(method = RequestMethod.POST)
public String create(@Valid UploadForm UploadForm, BindingResult result){
if (result.hasErrors())
{
for(ObjectError error : result.getAllErrors())
{
System.err.println("Error: " + error.getCode() + " - " + error.getDefaultMessage());
}
return "/pages/upload";
}
// Some type of file processing...
System.err.println("-------------------------------------------");
//.getOriginalFilename()
System.err.println("Test upload: " + UploadForm.getFileData());
System.err.println("-------------------------------------------");
return "redirect:/pages/upload";
}
}
模型:
public class UploadForm {
private CommonsMultipartFile fileData;
public CommonsMultipartFile getFileData() {
System.out.println("REACHED GET METHOD");
return fileData;
}
public void setFileData(CommonsMultipartFile fileData) {
System.out.println("REACHED SET METHOD");
this.fileData = fileData;
}
}
我是 Spring 和 MVC 的新手,但我正在慢慢掌握它。这里的问题是我实际上正在输入控制器的public String create(@Valid UploadForm UploadForm, BindingResult result)
方法,但是 UploadForm 被作为空值传递,而我终其一生都无法弄清楚,这让我非常沮丧。任何帮助或提示将不胜感激。谢谢!