Spring MVC实现文件上传

本文详细介绍了如何使用SpringMVC内置的MultipartResolver解析器实现文件上传功能,包括配置解析器、创建HTML表单、处理上传请求及错误处理等步骤。

spring mvc 支持web应用程序的文件上传功能,是由spring内置的即插即用的MultipartResolver来实现的,这些解析器都定义在org.springframework.web.multipart包里。下面将使用CommonsMultipartResolver解析器来实现简单的文件上传功能。

    在web应用程序上下文配置文件中(我的配置文件名为 /WEB-INF/config/app-config.xml)定义如下:

Xml代码  收藏代码
  1. <bean id="multipartResolver"
  2. class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  3. <!-- 以字节为单位的最大上传文件的大小 -->
  4. <property name="maxUploadSize" value="100000" />
  5. </bean>


加入两个依赖的jar包(spring官网可以下载到对应版本的常用依赖jar包):

com.springsource.org.apache.commons.io-1.4.0.jar
    com.springsource.org.apache.commons.fileupload-1.2.0.jar

创建一个HTML表单:

Html代码  收藏代码
  1. <body>
  2. <h1>
  3.   Spring MVC 3.0 文件上传测试 
  4. </h1>   //action里的html是后缀名,不是HTML文件,用于spring对请求进行拦截判断 
  5. <form. method="post" action="upload.html" enctype="multipart/form-data">
  6. <input type="text" name="name" />
  7. <input type="file" name="file" />
  8. <input type="submit" />
  9. </form>
  10. </body>



创建一个controller(控制器)来处理文件上传请求,FileUploadController.java:

Java代码  收藏代码
  1. @Controller //声明该类为控制器类
  2. public class FileUploadController implements ServletContextAware{ //实现ServletContextAware接口,获取本地路径
  3. private ServletContext servletContext; 
  4. public void setServletContext(ServletContext servletContext) { //实现接口中的setServletContext方法
  5. this.servletContext = servletContext; 
  6. @RequestMapping(value = "/upload", method = RequestMethod.POST) //将文件上传请求映射到该方法
  7. public String handleFormUpload(@RequestParam("name") String name, //设置请求参数的名称和类型
  8. @RequestParam("file") CommonsMultipartFile mFile) { //请求参数一定要与form中的参数名对应
  9. if (!mFile.isEmpty()) { 
  10.    String path = this.servletContext.getRealPath("/tmp/");  //获取本地存储路径
  11. File file = new File(path + new Date().getTime() + ".jpg"); //新建一个文件
  12. try
  13.     mFile.getFileItem().write(file); //将上传的文件写入新建的文件中
  14. } catch (Exception e) { 
  15.     e.printStackTrace(); 
  16.    } 
  17. return "redirect:uploadSuccess"; //返回成功视图
  18. }else
  19. return "redirect:uploadFailure"; //返回失败视图
  20. }  
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值