SpringMVC之檔案上傳

HuskySir發表於2020-06-20

一、環境搭建

1、新建專案

(1)在” main”目錄下新建” java”與” resources”目錄

(2)將” java”設定為”Sources Root”

(3)將” resources”設定為”Resources Root”

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

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

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

(7)在”WEB-INF”目錄下新建資料夾”Pages”

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

2、整體框架

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伺服器

二、檔案上傳

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"右側的執行按鈕

選擇檔案然後進行上傳

點選上傳按鈕後,執行成功,跳到"success.jsp"介面顯示跳轉成功

在IDEA輸出臺檢視檔案路徑

按照路徑檢視檔案是否上傳成功

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"右側的執行按鈕

選擇檔案然後進行上傳

點選上傳按鈕後,執行成功,跳到"success.jsp"介面顯示跳轉成功

在IDEA輸出臺檢視檔案路徑

按照路徑檢視檔案是否上傳成功

3、跨伺服器上傳檔案

(1)新建”FileuploadServer”專案(過程不再演示)

不需要建立”java””resources”等資料夾,只需要”index.jsp”顯示介面即可

“index.jsp”程式碼

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

(2)配置伺服器

點選”Edit Configurations”配置Tomcat伺服器

為與”SpringMVC”伺服器區分,修改”HTTP port”為”9090”,修改”JMX port”為”1090”

(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"伺服器

在"FileuploadServer"專案的"target/FileuploadServer/"目錄下新建資料夾"uploads"

選擇檔案並進行上傳,上傳成功跳轉到"success.jsp"

檢視IDEA輸出資訊

此時路徑應為"FileuploadServer/target/FileuploadServer/uploads",在路徑下檢視檔案是否上傳成功

三、注意事項

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"

此時IEDA輸出為

web.xml檔案修改處原內容

應修改為

修改後的程式碼

 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的錯誤

四、完整程式碼

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>

學習資料來源:黑馬程式設計師

相關文章