使用Spring MVC上传文件(多个文件)时出现以下错误。
java.lang.NullPointerException
com.mkyong.common.controller.FileUploadController.save(FileUploadController.java:34)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
java.lang.reflect.Method.invoke(Method.java:597)
JSP
<form:form method="post" action="save"
modelAttribute="uploadForm" enctype="multipart/form-data">
<p>Select files to upload. Press Add button to add more file inputs.</p>
<input id="addFile" type="button" value="Add File" />
<table id="fileTable">
<tr>
<td><input name="files[0]" type="file" /></td>
</tr>
<tr>
<td><input name="files[1]" type="file" /></td>
</tr>
</table>
<br/><input type="submit" value="Upload" />
</form:form>
控制器
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(
@ModelAttribute("uploadForm") FileUploadForm uploadForm,
Model map) {
List<MultipartFile> files = uploadForm.getFiles();
List<String> fileNames = new ArrayList<String>();
//counting the file size
System.out.println("Files count :"+files.size());
if(null != files && files.size() > 0) { //HERE 'files' is NULL
for (MultipartFile multipartFile : files) {
String fileName = multipartFile.getOriginalFilename();
fileNames.add(fileName);
//Handle file content - multipartFile.getInputStream()
}
}
有人可以帮我解决这个问题吗?我仍在调试为什么我无法将文件(uploadForm)从jsp传递给控制器。
答案 0 :(得分:1)
我刚解决了。您需要在dispatcher-servlet.xml中添加<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
。
如果您对多个文件使用多部分数组,那么只使用数组名称。像
private MultipartFile [] file;
Getters and Setters and form
<form:form commandName="uploadFile" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="file" name="file"/>
<input type="file" name="file"/>
<input type="submit" value="Submit"/>
</form:form>