我正在尝试从客户端计算机上传文件到服务器目录。我使用了以下代码:
FileUpload.jsp
<form:form commandName="fileUpload" action="upload.action" method="post" enctype="multipart/form-data">
<form:label path="fileData">Upload a File</form:label> <br />
<form:input type="file" path="fileData" />
<input type="submit" value="upload" >
</form:form>
在我的控制器中:
@RequestMapping("/upload.action")
public String upload(@ModelAttribute("fileUpload") FileUpload fileUpload,HttpServletResponse response,Model model)
{
CommonsMultipartFile multipartFile = fileUpload.getFileData();
String orginalName = multipartFile.getOriginalFilename();
String filePath = "/my_uploads/"+orginalName;
File destination = new File(filePath);
String status ="success";
try {
multipartFile.transferTo(destination);
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
status="failure";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
status="iofailure";
}
model.addAttribute("status", status);
return "home";
}
FileUpload.java:
{
private CommonsMultipartFile fileData;
....
}
NullPointerException
被抛到String orginalName = multipartFile.getOriginalFilename();
行......我做错了什么?
答案 0 :(得分:6)
尝试在请求处理程序中添加MultipartFile
作为参数。
@RequestMapping("/upload.action")
public String upload(@RequestParam(value = "file") MultipartFile file,
HttpServletResponse response,Model model)
{
//Controller logic...
}
这将要求您在调度员的配置中注册一个新的bean。
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5000000"/>
</bean>
答案 1 :(得分:0)
@RequestMapping("/upload.action")
public String upload(@RequestParam("fileData") MultipartFile file,
HttpServletResponse response,Model model)
{
//Controller logic...
}
您的请求处理程序方法的参数应该具有相同的名称,无论您在multipartFile的FileUpload Pojo中提供什么(&#34; fileData&#34;)它都应该在参数
中谢谢,