转载

SpringMVC之文件上传

一、环境搭建

1、新建项目

SpringMVC之文件上传

SpringMVC之文件上传

SpringMVC之文件上传

SpringMVC之文件上传

(1)在” main”目录下新建” java”与” resources”目录

SpringMVC之文件上传

(2)将” java”设置为”Sources Root”

SpringMVC之文件上传

(3)将” resources”设置为”Resources Root”

SpringMVC之文件上传

(4)在”java”目录下新建”StudyProject.Controller”包

SpringMVC之文件上传

(5)在”StudyProject.Controller”包下新建”TestController”类

SpringMVC之文件上传

(6)在”resources”目录下新建”Spring.xml”

SpringMVC之文件上传

(7)在”WEB-INF”目录下新建文件夹”Pages”

SpringMVC之文件上传

(8)在“Pages”目录下新建”success.jsp”

SpringMVC之文件上传

2、整体框架

SpringMVC之文件上传

3、TestController类和success.jsp

(1)TestController类

原代码

1 package StudyProject.Controller;
2 
3 public class TestController {
4 }

编写前端控制器及路径

修改后

1 package StudyProject.Controller;
2 
3 import org.springframework.stereotype.Controller;
4 import org.springframework.web.bind.annotation.RequestMapping;
5 
6 @Controller
7 @RequestMapping(path="/testController")
8 public class TestController {
9 }

(2)success.jsp

原代码

1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
2 <html>
3 <head>
4     <title>Title</title>
5 </head>
6 <body>
7 
8 </body>
9 </html>

添加一个跳转成功提示

修改后

 1 <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
 2 <html>
 3 <head>
 4     <title>Title</title>
 5 </head>
 6 <body>
 7 
 8     <h3>跳转成功</h3>
 9 
10 </body>
11 </html>

4、配置文件

(1)pom.xml

原代码

1   <properties>
2     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
3     <maven.compiler.source>1.7</maven.compiler.source>
4     <maven.compiler.target>1.7</maven.compiler.target>
5   </properties>

修改版本,并且加上spring.version

修改后

1   <properties>
2     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
3     <maven.compiler.source>14.0.1</maven.compiler.source>
4     <maven.compiler.target>14.0.1</maven.compiler.target>
5     <spring.version>5.0.2.RELEASE</spring.version>
6   </properties>

原代码

1   <dependencies>
2     <dependency>
3       <groupId>junit</groupId>
4       <artifactId>junit</artifactId>
5       <version>4.11</version>
6       <scope>test</scope>
7     </dependency>
8   </dependencies>

在<dependencies></dependency>里加入坐标依赖,原有的可以删去

修改后

 1   <!-- 导入坐标依赖 -->
 2   <dependencies>
 3     <dependency>
 4       <groupId>org.springframework</groupId>
 5       <artifactId>spring-context</artifactId>
 6       <version>${spring.version}</version>
 7     </dependency>
 8     <dependency>
 9       <groupId>org.springframework</groupId>
10       <artifactId>spring-web</artifactId>
11       <version>${spring.version}</version>
12     </dependency>
13     <dependency>
14       <groupId>org.springframework</groupId>
15       <artifactId>spring-webmvc</artifactId>
16       <version>${spring.version}</version>
17     </dependency>
18     <dependency>
19       <groupId>javax.servlet</groupId>
20       <artifactId>servlet-api</artifactId>
21       <version>2.5</version>
22       <scope>provided</scope>
23     </dependency>
24     <dependency>
25       <groupId>javax.servlet.jsp</groupId>
26       <artifactId>jsp-api</artifactId>
27       <version>2.0</version>
28       <scope>provided</scope>
29     </dependency>
30   </dependencies>

(2)web.xml

原代码

1 <!DOCTYPE web-app PUBLIC
2  "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
3  "http://java.sun.com/dtd/web-app_2_3.dtd" >
4 
5 <web-app>
6   <display-name>Archetype Created Web Application</display-name>
7 </web-app>

配置前段控制器与解决中文乱码的过滤器

修改后

 1 <!DOCTYPE web-app PUBLIC
 2  "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 3  "http://java.sun.com/dtd/web-app_2_3.dtd" >
 4 
 5 <web-app>
 6   <display-name>Archetype Created Web Application</display-name>
 7 
 8   <!--配置解决中文乱码的过滤器-->
 9   <filter>
10     <filter-name>characterEncodingFilter</filter-name>
11     <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
12     <init-param>
13       <param-name>encoding</param-name>
14       <param-value>UTF-8</param-value>
15     </init-param>
16   </filter>
17   <filter-mapping>
18   <filter-name>characterEncodingFilter</filter-name>
19   <url-pattern>/*</url-pattern>
20   </filter-mapping>
21 
22   <!-- 配置前端控制器 -->
23   <servlet>
24     <servlet-name>dispatcherServlet</servlet-name>
25     <!-- 创建前端控制器DispatcherServlet对象 -->
26     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
27     <!-- 使前端控制器初始化时读取Spring.xml文件创建Spring核心容器 -->
28     <init-param>
29       <param-name>contextConfigLocation</param-name>
30       <param-value>classpath*:Spring.xml</param-value>
31     </init-param>
32     <!-- 设置该Servlet的优先级别为最高,使之最早创建(在应用启动时就加载并初始化这个servlet -->
33     <load-on-startup>1</load-on-startup>
34   </servlet>
35   <servlet-mapping>
36     <servlet-name>dispatcherServlet</servlet-name>
37     <url-pattern>/</url-pattern>
38   </servlet-mapping>
39 
40 </web-app>

(3)Spring.xml

原代码

1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
5 
6 </beans>

配置spring创建容器时扫描的包、视图解析器、开启spring注解支持等

修改后

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:mvc="http://www.springframework.org/schema/mvc"
 4        xmlns:context="http://www.springframework.org/schema/context"
 5        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 6        xsi:schemaLocation="
 7         http://www.springframework.org/schema/beans
 8         http://www.springframework.org/schema/beans/spring-beans.xsd
 9         http://www.springframework.org/schema/mvc
10         http://www.springframework.org/schema/mvc/spring-mvc.xsd
11         http://www.springframework.org/schema/context
12         http://www.springframework.org/schema/context/spring-context.xsd">
13 
14     <!-- 配置spring创建容器时扫描的包 -->
15     <context:component-scan base-package="StudyProject.Controller"></context:component-scan>
16 
17     <!-- 配置视图解析器,用于解析项目跳转到的文件的位置 -->
18     <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
19         <!-- 寻找包的路径 -->
20         <property name="prefix" value="/WEB-INF/pages/"></property>
21         <!-- 寻找文件的后缀名 -->
22         <property name="suffix" value=".jsp"></property>
23     </bean>
24 
25     <!-- 配置spring开启注解mvc的支持 -->
26     <mvc:annotation-driven></mvc:annotation-driven>
27 </beans>

5、Tomcat服务器(本地已建SpringMVC项目,Spring_MVC项目仅做示范)

点击”Add Configurations”配置Tomcat服务器

SpringMVC之文件上传

SpringMVC之文件上传

SpringMVC之文件上传

SpringMVC之文件上传

SpringMVC之文件上传

二、文件上传

1、传统方式上传文件

(1)TestController类

在控制器内部新增"testMethod_Traditional"方法

 1 @Controller
 2 @RequestMapping(path="/testController")
 3 public class TestController {
 4 
 5     @RequestMapping(path="/testMethod_Traditional")
 6     public String testMethod_Traditional(HttpServletRequest request) throws Exception {
 7         System.out.println("执行了testMethod_Traditional方法");
 8 
 9         //获取文件上传目录
10         String path = request.getSession().getServletContext().getRealPath("/uploads");
11         //创建file对象
12         File file = new File(path);
13         //判断路径是否存在,若不存在,创建该路径
14         if (!file.exists()) {
15             file.mkdir();
16         }
17 
18         //创建磁盘文件项工厂
19         DiskFileItemFactory factory = new DiskFileItemFactory();
20         ServletFileUpload fileUpload = new ServletFileUpload(factory);
21         //解析request对象
22         List<FileItem> list = fileUpload.parseRequest(request);
23         //遍历
24         for (FileItem fileItem:list) {
25             // 判断文件项是普通字段,还是上传的文件
26             if (fileItem.isFormField()) {
27                 //普通字段
28             } else {
29                 //上传文件项
30                 //获取上传文件项的名称
31                 String filename = fileItem.getName();
32                 String uuid = UUID.randomUUID().toString().replaceAll("-","").toUpperCase();
33                 filename = uuid+"_"+filename;
34                 //上传文件
35                 fileItem.write(new File(file,filename));
36                 //删除临时文件
37                 fileItem.delete();
38             }
39         }
40 
41         System.out.println("上传路径:"+path);
42         System.out.println("上传成功");
43         return "success";
44     }
45 
46 }

(2)index.jsp

添加form表单

1     <form action="testController/testMethod_Traditional" method="post" enctype="multipart/form-data">
2         图片 <input type="file" name="uploadfile_Traditional"> <br>
3         <input type="submit" value="传统方式上传文件">
4     </form>

(3)结果演示

点击服务器"SpringMVC"右侧的运行按钮

SpringMVC之文件上传

选择文件然后进行上传

SpringMVC之文件上传

点击上传按钮后,执行成功,跳到"success.jsp"界面显示跳转成功

SpringMVC之文件上传

在IDEA输出台查看文件路径

SpringMVC之文件上传

按照路径查看文件是否上传成功

SpringMVC之文件上传

2、SpringMVC方式上传文件

(1)pom.xml添加文件上传坐标依赖

在pom.xml文件<dependencies></dependencies>内添加文件上传坐标依赖

 1     <!-- 文件上传 -->
 2     <dependency>
 3       <groupId>commons-fileupload</groupId>
 4       <artifactId>commons-fileupload</artifactId>
 5       <version>1.3.1</version>
 6     </dependency>
 7     <dependency>
 8       <groupId>commons-io</groupId>
 9       <artifactId>commons-io</artifactId>
10       <version>2.4</version>
11     </dependency>

(2)Spring.xml配置文件解析器对象

在Spring.xml文件<beans></beans>内配置文件解析器对象

1     <!-- 配置文件解析器对象 -->
2     <bean id="multipartResolver"
3           class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
4         <property name="defaultEncoding" value="utf-8"></property>
5         <property name="maxUploadSize" value="10485760"></property>
6     </bean>

(3)TestController类

在控制器内部新增"testMethod_SpringMVC"方法

 1 @Controller
 2 @RequestMapping(path="/testController")
 3 public class TestController {
 4 
 5     @RequestMapping(path="/testMethod_SpringMVC")
 6     public String testMethod_SpringMVC(HttpServletRequest request,MultipartFile uploadfile_SpringMVC) throws Exception {
 7         System.out.println("执行了testMethod_SpringMVC方法");
 8 
 9         //获取文件上传目录
10         String path = request.getSession().getServletContext().getRealPath("/uploads");
11         //创建file对象
12         File file = new File(path);
13         //判断路径是否存在,若不存在,创建该路径
14         if (!file.exists()) {
15             file.mkdir();
16         }
17 
18         //获取到上传文件的名称
19         String filename = uploadfile_SpringMVC.getOriginalFilename();
20         String uuid = UUID.randomUUID().toString().replaceAll("-","").toUpperCase();
21         filename = uuid+"_"+filename;
22         //上传文件
23         uploadfile_SpringMVC.transferTo(new File(file,filename));
24 
25         System.out.println("上传路径:"+path);
26         System.out.println("上传成功");
27         return "success";
28     }
29 
30 }

(4)index.jsp

添加form表单

1     <form action="testController/testMethod_SpringMVC" method="post" enctype="multipart/form-data">
2         图片 <input type="file" name="uploadfile_SpringMVC"> <br>
3         <input type="submit" value="SpringMVC上传文件">
4     </form>

(5)结果演示

点击服务器"SpringMVC"右侧的运行按钮

SpringMVC之文件上传

选择文件然后进行上传

SpringMVC之文件上传

点击上传按钮后,执行成功,跳到"success.jsp"界面显示跳转成功

SpringMVC之文件上传

在IDEA输出台查看文件路径

SpringMVC之文件上传

按照路径查看文件是否上传成功

SpringMVC之文件上传

3、跨服务器上传文件

(1)新建”FileuploadServer”项目(过程不再演示)

不需要建立”java””resources”等文件夹,只需要”index.jsp”显示界面即可

SpringMVC之文件上传

“index.jsp”代码

1 <html>
2 <body>
3 <h2>Hello! FileuploadServer</h2>
4 </body>
5 </html>

(2)配置服务器

点击”Edit Configurations”配置Tomcat服务器

SpringMVC之文件上传

SpringMVC之文件上传

SpringMVC之文件上传

SpringMVC之文件上传

为与”SpringMVC”服务器区分,修改”HTTP port”为”9090”,修改”JMX port”为”1090”

SpringMVC之文件上传

(3)pom.xml添加跨服务器文件上传坐标依赖

 1     <!-- 跨服务器文件上传 -->
 2     <dependency>
 3       <groupId>com.sun.jersey</groupId>
 4       <artifactId>jersey-core</artifactId>
 5       <version>1.18.1</version>
 6     </dependency>
 7     <dependency>
 8       <groupId>com.sun.jersey</groupId>
 9       <artifactId>jersey-client</artifactId>
10       <version>1.18.1</version>
11     </dependency>

(4)TestController类

在控制器内部新增"testMethod_AcrossServer"方法

 1 @Controller
 2 @RequestMapping(path="/testController")
 3 public class TestController {
 4 
 5     @RequestMapping(path="/testMethod_AcrossServer")
 6     public String testMethod_AcrossServer(MultipartFile uploadfile_AcrossServer) throws Exception {
 7         System.out.println("执行了testMethod_AcrossServer方法");
 8 
 9         //定义上传文件服务器路径
10         String path = "http://localhost:9090/FileuploadServer_war_exploded/uploads/";
11 
12         //获取到上传文件的名称
13         String filename = uploadfile_AcrossServer.getOriginalFilename();
14         String uuid = UUID.randomUUID().toString().replaceAll("-","").toUpperCase();
15         filename = uuid+"_"+filename;
16 
17         //创建客户端对象
18         Client client = Client.create();
19         //连接图片服务器
20         WebResource webResourcer = client.resource(path+filename);
21         //向图片服务器上传文件
22         webResourcer.put(uploadfile_AcrossServer.getBytes());
23 
24         System.out.println("上传路径:"+path);
25         System.out.println("上传成功");
26         return "success";
27     }
28 
29 }

(5)index.jsp

添加form表单

1     <form action="testController/testMethod_AcrossServer" method="post" enctype="multipart/form-data">
2         图片 <input type="file" name="uploadfile_AcrossServer"> <br>
3         <input type="submit" value="跨服务器上传文件">
4     </form>

(6)结果演示

运行"FileuploadServer"服务器

SpringMVC之文件上传

SpringMVC之文件上传

运行"SpringMVC"服务器

SpringMVC之文件上传

SpringMVC之文件上传

在"FileuploadServer"项目的"target/FileuploadServer/"目录下新建文件夹"uploads"

SpringMVC之文件上传

SpringMVC之文件上传

选择文件并进行上传,上传成功跳转到"success.jsp"

SpringMVC之文件上传

查看IDEA输出信息

SpringMVC之文件上传

此时路径应为"FileuploadServer/target/FileuploadServer/uploads",在路径下查看文件是否上传成功

SpringMVC之文件上传

三、注意事项

1、传统方式上传文件

传统方式上传时不需要在Spring.xml内配置文件解析器对象 使用该方法时需要注释掉该对象,否则会造成运行成功但上传文件为空。

1     <!-- 配置文件解析器对象 -->
2     <bean id="multipartResolver"
3           class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
4         <property name="defaultEncoding" value="utf-8"></property>
5         <property name="maxUploadSize" value="10485760"></property>
6     </bean>

即使用传统方式上传文件时,应当注释掉该段代码

2、跨服务器上传文件

(1) 需要修改Tomcat服务器的web.xml配置文件的权限, 增加可以写入的权限,否则会出现405的错误。 如我所下载的Tomcat-9.0.36的web.xml路径为"apache-tomcat-9.0.36/conf/web.xml"

SpringMVC之文件上传

此时IEDA输出为

SpringMVC之文件上传

web.xml文件修改处原内容

SpringMVC之文件上传

应修改为

SpringMVC之文件上传

修改后的代码

 1     <servlet>
 2         <servlet-name>default</servlet-name>
 3         <servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
 4         <init-param>
 5             <param-name>debug</param-name>
 6             <param-value>0</param-value>
 7         </init-param>
 8         <init-param>
 9             <param-name>listings</param-name>
10             <param-value>false</param-value>
11         </init-param>
12         <init-param>
13             <param-name>readonly</param-name>
14             <param-value>false</param-value>
15         </init-param>
16         <load-on-startup>1</load-on-startup>
17     </servlet>

(2)在跨服务器上传文件时, 需要在"FileuploadServer"项目的"target/FileuploadServer/"目录下新建文件夹"uploads",否则会出现409的错误

SpringMVC之文件上传

四、完整代码

1、pom.xml(SpringMVC)

  1 <?xml version="1.0" encoding="UTF-8"?>
  2 
  3 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5   <modelVersion>4.0.0</modelVersion>
  6 
  7   <groupId>org.example</groupId>
  8   <artifactId>SpringMVC</artifactId>
  9   <version>1.0-SNAPSHOT</version>
 10   <packaging>war</packaging>
 11 
 12   <name>SpringMVC Maven Webapp</name>
 13   <!-- FIXME change it to the project's website -->
 14   <url>http://www.example.com</url>
 15 
 16   <properties>
 17     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 18     <maven.compiler.source>14.0.1</maven.compiler.source>
 19     <maven.compiler.target>14.0.1</maven.compiler.target>
 20     <spring.version>5.0.2.RELEASE</spring.version>
 21   </properties>
 22 
 23   <!-- 导入坐标依赖 -->
 24   <dependencies>
 25     <dependency>
 26       <groupId>org.springframework</groupId>
 27       <artifactId>spring-context</artifactId>
 28       <version>${spring.version}</version>
 29     </dependency>
 30     <dependency>
 31       <groupId>org.springframework</groupId>
 32       <artifactId>spring-web</artifactId>
 33       <version>${spring.version}</version>
 34     </dependency>
 35     <dependency>
 36       <groupId>org.springframework</groupId>
 37       <artifactId>spring-webmvc</artifactId>
 38       <version>${spring.version}</version>
 39     </dependency>
 40     <dependency>
 41       <groupId>javax.servlet</groupId>
 42       <artifactId>servlet-api</artifactId>
 43       <version>2.5</version>
 44       <scope>provided</scope>
 45     </dependency>
 46     <dependency>
 47       <groupId>javax.servlet.jsp</groupId>
 48       <artifactId>jsp-api</artifactId>
 49       <version>2.0</version>
 50       <scope>provided</scope>
 51     </dependency>
 52 
 53     <!-- 文件上传(采用传统方式上传时需注释掉该部分) -->
 54     <dependency>
 55       <groupId>commons-fileupload</groupId>
 56       <artifactId>commons-fileupload</artifactId>
 57       <version>1.3.1</version>
 58     </dependency>
 59     <dependency>
 60       <groupId>commons-io</groupId>
 61       <artifactId>commons-io</artifactId>
 62       <version>2.4</version>
 63     </dependency>
 64 
 65     <!-- 跨服务器文件上传 -->
 66     <dependency>
 67       <groupId>com.sun.jersey</groupId>
 68       <artifactId>jersey-core</artifactId>
 69       <version>1.18.1</version>
 70     </dependency>
 71     <dependency>
 72       <groupId>com.sun.jersey</groupId>
 73       <artifactId>jersey-client</artifactId>
 74       <version>1.18.1</version>
 75     </dependency>
 76 
 77   </dependencies>
 78 
 79   <build>
 80     <finalName>SpringMVC</finalName>
 81     <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
 82       <plugins>
 83         <plugin>
 84           <artifactId>maven-clean-plugin</artifactId>
 85           <version>3.1.0</version>
 86         </plugin>
 87         <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
 88         <plugin>
 89           <artifactId>maven-resources-plugin</artifactId>
 90           <version>3.0.2</version>
 91         </plugin>
 92         <plugin>
 93           <artifactId>maven-compiler-plugin</artifactId>
 94           <version>3.8.0</version>
 95         </plugin>
 96         <plugin>
 97           <artifactId>maven-surefire-plugin</artifactId>
 98           <version>2.22.1</version>
 99         </plugin>
100         <plugin>
101           <artifactId>maven-war-plugin</artifactId>
102           <version>3.2.2</version>
103         </plugin>
104         <plugin>
105           <artifactId>maven-install-plugin</artifactId>
106           <version>2.5.2</version>
107         </plugin>
108         <plugin>
109           <artifactId>maven-deploy-plugin</artifactId>
110           <version>2.8.2</version>
111         </plugin>
112       </plugins>
113     </pluginManagement>
114   </build>
115 </project>

2、web.xml(SpringMVC)

 1 <!DOCTYPE web-app PUBLIC
 2  "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 3  "http://java.sun.com/dtd/web-app_2_3.dtd" >
 4 
 5 <web-app>
 6   <display-name>Archetype Created Web Application</display-name>
 7 
 8   <!--配置解决中文乱码的过滤器-->
 9   <filter>
10     <filter-name>characterEncodingFilter</filter-name>
11     <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
12     <init-param>
13       <param-name>encoding</param-name>
14       <param-value>UTF-8</param-value>
15     </init-param>
16   </filter>
17   <filter-mapping>
18   <filter-name>characterEncodingFilter</filter-name>
19   <url-pattern>/*</url-pattern>
20   </filter-mapping>
21 
22   <!-- 配置前端控制器 -->
23   <servlet>
24     <servlet-name>dispatcherServlet</servlet-name>
25     <!-- 创建前端控制器DispatcherServlet对象 -->
26     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
27     <!-- 使前端控制器初始化时读取Spring.xml文件创建Spring核心容器 -->
28     <init-param>
29       <param-name>contextConfigLocation</param-name>
30       <param-value>classpath*:Spring.xml</param-value>
31     </init-param>
32     <!-- 设置该Servlet的优先级别为最高,使之最早创建(在应用启动时就加载并初始化这个servlet -->
33     <load-on-startup>1</load-on-startup>
34   </servlet>
35   <servlet-mapping>
36     <servlet-name>dispatcherServlet</servlet-name>
37     <url-pattern>/</url-pattern>
38   </servlet-mapping>
39 
40 </web-app>

3、Spring.xml(SpringMVC)

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:mvc="http://www.springframework.org/schema/mvc"
 4        xmlns:context="http://www.springframework.org/schema/context"
 5        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 6        xsi:schemaLocation="
 7         http://www.springframework.org/schema/beans
 8         http://www.springframework.org/schema/beans/spring-beans.xsd
 9         http://www.springframework.org/schema/mvc
10         http://www.springframework.org/schema/mvc/spring-mvc.xsd
11         http://www.springframework.org/schema/context
12         http://www.springframework.org/schema/context/spring-context.xsd">
13 
14     <!-- 配置spring创建容器时扫描的包 -->
15     <context:component-scan base-package="StudyProject.Controller"></context:component-scan>
16 
17     <!-- 配置视图解析器,用于解析项目跳转到的文件的位置 -->
18     <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
19         <!-- 寻找包的路径 -->
20         <property name="prefix" value="/WEB-INF/pages/"></property>
21         <!-- 寻找文件的后缀名 -->
22         <property name="suffix" value=".jsp"></property>
23     </bean>
24 
25     <!-- 配置文件解析器对象 -->
26     <bean id="multipartResolver"
27           class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
28         <property name="defaultEncoding" value="utf-8"></property>
29         <property name="maxUploadSize" value="10485760"></property>
30     </bean>
31     
32     <!-- 配置spring开启注解mvc的支持 -->
33     <mvc:annotation-driven></mvc:annotation-driven>
34 </beans>

4、TestController类(SpringMVC)

  1 package StudyProject.Controller;
  2 
  3 import com.sun.jersey.api.client.Client;
  4 import com.sun.jersey.api.client.WebResource;
  5 import org.apache.commons.fileupload.FileItem;
  6 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
  7 import org.apache.commons.fileupload.servlet.ServletFileUpload;
  8 import org.springframework.stereotype.Controller;
  9 import org.springframework.web.bind.annotation.RequestMapping;
 10 import org.springframework.web.multipart.MultipartFile;
 11 import javax.servlet.http.HttpServletRequest;
 12 import java.io.File;
 13 import java.util.List;
 14 import java.util.UUID;
 15 
 16 @Controller
 17 @RequestMapping(path="/testController")
 18 public class TestController {
 19 
 20     @RequestMapping(path="/testMethod_Traditional")
 21     public String testMethod_Traditional(HttpServletRequest request) throws Exception {
 22         System.out.println("执行了testMethod_Traditional方法");
 23 
 24         //获取文件上传目录
 25         String path = request.getSession().getServletContext().getRealPath("/uploads");
 26         //创建file对象
 27         File file = new File(path);
 28         //判断路径是否存在,若不存在,创建该路径
 29         if (!file.exists()) {
 30             file.mkdir();
 31         }
 32 
 33         //创建磁盘文件项工厂
 34         DiskFileItemFactory factory = new DiskFileItemFactory();
 35         ServletFileUpload fileUpload = new ServletFileUpload(factory);
 36         //解析request对象
 37         List<FileItem> list = fileUpload.parseRequest(request);
 38         //遍历
 39         for (FileItem fileItem:list) {
 40             // 判断文件项是普通字段,还是上传的文件
 41             if (fileItem.isFormField()) {
 42                 //普通字段
 43             } else {
 44                 //上传文件项
 45                 //获取上传文件项的名称
 46                 String filename = fileItem.getName();
 47                 String uuid = UUID.randomUUID().toString().replaceAll("-","").toUpperCase();
 48                 filename = uuid+"_"+filename;
 49                 //上传文件
 50                 fileItem.write(new File(file,filename));
 51                 //删除临时文件
 52                 fileItem.delete();
 53             }
 54         }
 55 
 56         System.out.println("上传路径:"+path);
 57         System.out.println("上传成功");
 58         return "success";
 59     }
 60 
 61     @RequestMapping(path="/testMethod_SpringMVC")
 62     public String testMethod_SpringMVC(HttpServletRequest request,MultipartFile uploadfile_SpringMVC) throws Exception {
 63         System.out.println("执行了testMethod_SpringMVC方法");
 64 
 65         //获取文件上传目录
 66         String path = request.getSession().getServletContext().getRealPath("/uploads");
 67         //创建file对象
 68         File file = new File(path);
 69         //判断路径是否存在,若不存在,创建该路径
 70         if (!file.exists()) {
 71             file.mkdir();
 72         }
 73 
 74         //获取到上传文件的名称
 75         String filename = uploadfile_SpringMVC.getOriginalFilename();
 76         String uuid = UUID.randomUUID().toString().replaceAll("-","").toUpperCase();
 77         filename = uuid+"_"+filename;
 78         //上传文件
 79         uploadfile_SpringMVC.transferTo(new File(file,filename));
 80 
 81         System.out.println("上传路径:"+path);
 82         System.out.println("上传成功");
 83         return "success";
 84     }
 85 
 86     @RequestMapping(path="/testMethod_AcrossServer")
 87     public String testMethod_AcrossServer(MultipartFile uploadfile_AcrossServer) throws Exception {
 88         System.out.println("执行了testMethod_AcrossServer方法");
 89 
 90         //定义上传文件服务器路径
 91         String path = "http://localhost:9090/FileuploadServer_war_exploded/uploads/";
 92 
 93         //获取到上传文件的名称
 94         String filename = uploadfile_AcrossServer.getOriginalFilename();
 95         String uuid = UUID.randomUUID().toString().replaceAll("-","").toUpperCase();
 96         filename = uuid+"_"+filename;
 97 
 98         //创建客户端对象
 99         Client client = Client.create();
100         //连接图片服务器
101         WebResource webResourcer = client.resource(path+filename);
102         //向图片服务器上传文件
103         webResourcer.put(uploadfile_AcrossServer.getBytes());
104 
105         System.out.println("上传路径:"+path);
106         System.out.println("上传成功");
107         return "success";
108     }
109 
110 }

5、index.jsp(SpringMVC)

 1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 2 <html>
 3 <head>
 4     <title>Title</title>
 5 </head>
 6 <body>
 7 
 8     <form action="testController/testMethod_Traditional" method="post" enctype="multipart/form-data">
 9         图片 <input type="file" name="uploadfile_Traditional"> <br>
10         <input type="submit" value="传统方式上传文件">
11     </form>
12 
13     <br><br><br>
14 
15     <form action="testController/testMethod_SpringMVC" method="post" enctype="multipart/form-data">
16         图片 <input type="file" name="uploadfile_SpringMVC"> <br>
17         <input type="submit" value="SpringMVC上传文件">
18     </form>
19 
20     <br><br><br>
21 
22     <form action="testController/testMethod_AcrossServer" method="post" enctype="multipart/form-data">
23         图片 <input type="file" name="uploadfile_AcrossServer"> <br>
24         <input type="submit" value="跨服务器上传文件">
25     </form>
26 
27 </body>
28 </html>

6、success.jsp(SpringMVC)

 1 <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
 2 <html>
 3 <head>
 4     <title>Title</title>
 5 </head>
 6 <body>
 7 
 8     <h3>跳转成功</h3>
 9 
10 </body>
11 </html>

7、index.jsp(FileuploadServer)

1 <html>
2 <body>
3 <h2>Hello! FileuploadServer</h2>
4 </body>
5 </html>

学习资料来源:黑马程序员

原文  http://www.cnblogs.com/huskysir/p/13170179.html
正文到此结束
Loading...