2. SpringMVC 上传文件操作

1.创建java web项目:SpringMVCUploadDownFile

2.在项目的WebRoot下的WEB-INF的lib包下添加如下jar文件

 1 com.springsource.com.mchange.v2.c3p0-0.9.1.2.jar
 2 com.springsource.net.sf.cglib-2.2.0.jar
 3 com.springsource.org.aopalliance-1.0.0.jar
 4 com.springsource.org.apache.commons.fileupload-1.2.0.jar
 5 com.springsource.org.apache.commons.httpclient-3.1.0.jar
 6 com.springsource.org.apache.commons.lang-2.4.0.jar
 7 com.springsource.org.apache.commons.logging-1.1.1.jar
 8 com.springsource.org.apache.commons.pool-1.5.3.jar
 9 com.springsource.org.apache.log4j-1.2.15.jar
10 com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
11 com.springsource.org.codehaus.jackson.mapper-1.0.0.jar
12 commons-dbcp.jar
13 commons-fileupload-1.2.1.jar
14 commons-io-2.0.jar
15 jotm.jar
16 ojdbc14.jar
17 org.springframework.aop-3.0.1.RELEASE-A.jar
18 org.springframework.asm-3.0.1.RELEASE-A.jar
19 org.springframework.aspects-3.0.1.RELEASE-A.jar
20 org.springframework.beans-3.0.1.RELEASE-A.jar
21 org.springframework.context-3.0.1.RELEASE-A.jar
22 org.springframework.core-3.0.1.RELEASE-A.jar
23 org.springframework.expression-3.0.1.RELEASE-A.jar
24 org.springframework.instrument-3.0.1.RELEASE-A.jar
25 org.springframework.instrument.tomcat-3.0.1.RELEASE-A.jar
26 org.springframework.jdbc-3.0.1.RELEASE-A.jar
27 org.springframework.orm-3.0.1.RELEASE-A.jar
28 org.springframework.oxm-3.0.1.RELEASE-A.jar
29 org.springframework.transaction-3.0.1.RELEASE-A.jar
30 org.springframework.web-3.0.1.RELEASE-A.jar
31 org.springframework.web.portlet-3.0.1.RELEASE-A.jar
32 org.springframework.web.servlet-3.0.1.RELEASE-A.jar
33 org.springframework.web.struts-3.0.1.RELEASE-A.jar
34 persistence.jar
35 xapool.jar
项目中所需要的jar

3.在项目的WebRoot下的WEB-INF下添加springmvc-servlet.xml文件

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans" 
 3 xmlns:context="http://www.springframework.org/schema/context" 
 4 xmlns:mvc="http://www.springframework.org/schema/mvc" 
 5 xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
 6 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 7 xsi:schemaLocation="http://www.springframework.org/schema/beans 
 8 http://www.springframework.org/schema/beans/spring-beans.xsd 
 9 http://www.springframework.org/schema/context
10 http://www.springframework.org/schema/context/spring-context.xsd 
11 http://www.springframework.org/schema/mvc
12 http://www.springframework.org/schema/mvc/spring-mvc.xsd 
13 ">
14 <!-- 一。SpringMVC链接数据库步骤 -->
15 <!-- 1.mvc支持注解 -->
16 <mvc:annotation-driven/>
17 <!-- 2.全局扫描包 -->
18 <context:component-scan base-package="com"/>
19 
20 <!-- 3.驱动管理数据源 -->
21 <!-- 4.数据源事务管理 -->
22 <!-- 5.sqlsessionfactorybean -->
23 <!-- 6.spring和mybatis整合,映射输入参数 -->
24 
25 
26 <!--二。 上传下载配置 -->
27 
28 <!-- 1.springMVC上传文件时,需要配置CommonsMultipartResolver处理器 -->
29 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
30    <!-- 设置默认的编码格式 -->
31    <property name="defaultEncoding" value="UTF-8"/>
32    <!-- 指定所上传文件的总的大小不能超过200kb,
33         注意maxUploadSize属性点 限制 不是针对单个文件,
34         而是所有文件的容量总和-->
35    <property name="maxUploadSize" value="-1"/>
36 </bean>
37 
38 <!-- 2.springMVC在超出上传文件限制时,会抛出
39 org.springframework.web.multipart.MaxUploadSizeExceededException
40   该异常时SpringMVC在检查上传文件信息时抛出来的,而且此时还没有进入到Controller方法中
41  -->
42 <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
43   <property name="exceptionMappings">
44     <props>
45       <!-- 在遇到MaxUploadSizeExceededException异常时,自动跳到xxx面 -->
46       <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">error.jsp</prop>
47     </props>
48   </property>
49 </bean>
50 
51 
52 </beans>
springmvc-servlet.xml

4.在项目的WebRoot下添加index.jsp文件

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 <%
 3 String path = request.getContextPath();
 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6 
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11     
12     <title>上传文件</title>
13     <meta http-equiv="pragma" content="no-cache">
14     <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
15     <meta http-equiv="cache-control" content="no-cache">
16     <meta http-equiv="expires" content="0">    
17     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
18     <meta http-equiv="description" content="This is my page">
19     <!--
20     <link rel="stylesheet" type="text/css" href="styles.css">
21     -->
22   </head>
23   
24   <body>
25     <form action="<%=basePath%>upload.do" method="post" enctype="multipart/form-data">
26       <input type="hidden" name="holly" value="holly"/>
27       上传文件:<input type="file" name="uploadfile">
28       <input type="submit" value="上传">
29     </form>
30   </body>
31 </html>
index.jsp

5.在项目的WebRoot下添加success.jsp文件

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 <%
 3 String path = request.getContextPath();
 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6 
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11     
12     <title>My JSP 'index.jsp' starting page</title>
13     <meta http-equiv="pragma" content="no-cache">
14     <meta http-equiv="cache-control" content="no-cache">
15     <meta http-equiv="expires" content="0">    
16     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
17     <meta http-equiv="description" content="This is my page">
18     <!--
19     <link rel="stylesheet" type="text/css" href="styles.css">
20     -->
21   </head>
22   
23   <body>
24    文件上传成功
25   </body>
26 </html>
success.jsp

6.在项目的WebRoot下添加fail.jsp文件

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 <%
 3 String path = request.getContextPath();
 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6 
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11     
12     <title>My JSP 'index.jsp' starting page</title>
13     <meta http-equiv="pragma" content="no-cache">
14     <meta http-equiv="cache-control" content="no-cache">
15     <meta http-equiv="expires" content="0">    
16     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
17     <meta http-equiv="description" content="This is my page">
18     <!--
19     <link rel="stylesheet" type="text/css" href="styles.css">
20     -->
21   </head>
22   
23   <body>
24    文件上传失败
25   </body>
26 </html>
fail.jsp

7.在项目的WebRoot下添加error.jsp文件

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 <%
 3 String path = request.getContextPath();
 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6 
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11     
12     <title>My JSP 'index.jsp' starting page</title>
13     <meta http-equiv="pragma" content="no-cache">
14     <meta http-equiv="cache-control" content="no-cache">
15     <meta http-equiv="expires" content="0">    
16     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
17     <meta http-equiv="description" content="This is my page">
18     <!--
19     <link rel="stylesheet" type="text/css" href="styles.css">
20     -->
21   </head>
22   
23   <body>
24    文件上传异常
25   </body>
26 </html>
error.jsp

8.在项目的WebRoot下添加upload文件夹

9.在项目的src下的com.controller包下创建FileController.java文件

 1 package com.controller;
 2 
 3 import java.io.File;
 4 import java.io.IOException;
 5 
 6 import javax.servlet.http.HttpServletRequest;
 7 
 8 import org.apache.commons.io.FileUtils;
 9 import org.springframework.stereotype.Controller;
10 import org.springframework.web.bind.annotation.RequestMapping;
11 import org.springframework.web.bind.annotation.RequestParam;
12 import org.springframework.web.multipart.MultipartFile;
13 import org.springframework.web.multipart.commons.CommonsMultipartFile;
14 
15 @Controller
16 public class FileController {
17     /**
18      * 
19      * @param file 该属性使用得使用commons-io-2.0.jar文件,低版本不行
20      * @param request
21      * @return
22      */
23     @RequestMapping("/upload.do")
24     public String queryFileData(@RequestParam("uploadfile") CommonsMultipartFile file,HttpServletRequest request){
25         
26         /*MultipartFile是对当前上传的文件的封装,
27          * 当同时上传多个文件时,可以给定多个MultipartFile参数(数组)
28          */
29         if(file!=null){
30             System.out.println("文件对象接到了!");
31             
32             //获取文件名
33             String filename=file.getOriginalFilename();
34             System.out.println("filename:"+filename);
35             
36             //获取上传路径
37             String path=request.getSession().getServletContext().getRealPath("/upload/"+filename);
38             System.out.println("path:"+path);
39             
40             //创建文件流并指定写入路径
41             File destFile=new File(path);
42             
43                 //springmvc的方式
44                 //该方法自动操作,不需要额外的去关闭IO流
45                 //复制临时文件到指定文件夹下
46                 try {
47                     FileUtils.copyInputStreamToFile(file.getInputStream(), destFile);
48                     System.out.println("上传成功");
49                     return "/success.jsp";
50                 } catch (IOException e) {
51                     e.printStackTrace();
52                     System.out.println("上传失败");
53                     return "/error.jsp";
54                 }
55         }else{
56             System.out.println("文件没有对象接到了!");
57             return "/error.jsp";
58             
59         }
60     }
61 
62 }
FileController.java

10.有点困,结果自己测试肯定成功

原文地址:https://www.cnblogs.com/holly8/p/6087639.html