使用Spring MVC将文件上载到服务器目录 [英] File Upload to Server Directory Using Spring MVC

查看:347
本文介绍了使用Spring MVC将文件上载到服务器目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to upload a file to the server directory from client machine. I used the following codes :

FileUpload.jsp

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:

FileUpload.java :

{
   private CommonsMultipartFile fileData;
   ....
}

NullPointerException 抛出行 String orginalName = multipartFile.getOriginalFilename(); ..我做错了什么?

NullPointerException is thrown at the line String orginalName = multipartFile.getOriginalFilename(); .. what wrong thing i have done??

推荐答案

尝试在请求处理程序中添加 MultipartFile 作为参数。

Try adding the MultipartFile as a parameter in your requesthandler.

@RequestMapping("/upload.action")
public String upload(@RequestParam(value = "file") MultipartFile file,
        HttpServletResponse response,Model model)
{
    //Controller logic...
}

这将要求您在调度员的配置中注册一个新的bean。

This will require you to register a new bean in your dispatcher's configuration.

<bean id="multipartResolver"
   class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="5000000"/>
</bean>

这篇关于使用Spring MVC将文件上载到服务器目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆