使用Spring MVC将文件上载到服务器目录

时间:2012-12-31 12:21:46

标签: java spring spring-mvc

我正在尝试从客户端计算机上传文件到服务器目录。我使用了以下代码:

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();行......我做错了什么?

2 个答案:

答案 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;)它都应该在参数

谢谢,