4

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

文件上传.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";
}

文件上传.java:

{
   private CommonsMultipartFile fileData;
   ....
}

NullPointerException被扔在线上String orginalName = multipartFile.getOriginalFilename();..我做错了什么?

4

2 回答 2

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>
于 2012-12-31T12:27:29.963 回答
0
@RequestMapping("/upload.action")
public String upload(@RequestParam("fileData") MultipartFile file,
        HttpServletResponse response,Model model)
{
    //Controller logic...
}

您的请求处理程序方法的参数中应该有相同的名称,无论您在 FileUpload Pojo for multipartFile ("fileData") 中给出什么,它都应该在参数中

谢谢,

于 2015-08-18T12:44:35.847 回答