SpringMVC之文件上传

一、环境搭建

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 
3 
4     Title
5 
6 
7 
8 
9 

添加一个跳转成功提示

修改后

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

跳转成功

9 10 11

4、配置文件

(1)pom.xml

原代码

1   
2     UTF-8
3     1.7
4     1.7
5   

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

修改后

1   
2     UTF-8
3     14.0.1
4     14.0.1
5     5.0.2.RELEASE
6   

原代码

1   
2     
3       junit
4       junit
5       4.11
6       test
7     
8   

里加入坐标依赖,原有的可以删去

修改后

 1   
 2   
 3     
 4       org.springframework
 5       spring-context
 6       ${spring.version}
 7     
 8     
 9       org.springframework
10       spring-web
11       ${spring.version}
12     
13     
14       org.springframework
15       spring-webmvc
16       ${spring.version}
17     
18     
19       javax.servlet
20       servlet-api
21       2.5
22       provided
23     
24     
25       javax.servlet.jsp
26       jsp-api
27       2.0
28       provided
29     
30   

(2)web.xml

原代码

1 
4 
5 
6   Archetype Created Web Application
7 

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

修改后

 1 
 4 
 5 
 6   Archetype Created Web Application
 7 
 8   
 9   
10     characterEncodingFilter
11     org.springframework.web.filter.CharacterEncodingFilter
12     
13       encoding
14       UTF-8
15     
16   
17   
18   characterEncodingFilter
19   /*
20   
21 
22   
23   
24     dispatcherServlet
25     
26     org.springframework.web.servlet.DispatcherServlet
27     
28     
29       contextConfigLocation
30       classpath*:Spring.xml
31     
32     
33     1
34   
35   
36     dispatcherServlet
37     /
38   
39 
40 

(3)Spring.xml

原代码

1 
2 
5 
6 

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

修改后

 1 
 2 
13 
14     
15     
16 
17     
18     
19         
20         
21         
22         
23     
24 
25     
26     
27 

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 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     
2 图片
3 4

(3)结果演示

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

选择文件然后进行上传

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

在IDEA输出台查看文件路径

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

2、SpringMVC方式上传文件

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

在pom.xml文件内添加文件上传坐标依赖

 1     
 2     
 3       commons-fileupload
 4       commons-fileupload
 5       1.3.1
 6     
 7     
 8       commons-io
 9       commons-io
10       2.4
11     

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

在Spring.xml文件内配置文件解析器对象

1     
2     
4         
5         
6     

(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     
2 图片
3 4

(5)结果演示

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

选择文件然后进行上传

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

在IDEA输出台查看文件路径

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

3、跨服务器上传文件

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

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

“index.jsp”代码

1 
2 
3 

Hello! FileuploadServer

4 5

(2)配置服务器

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

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

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

 1     
 2     
 3       com.sun.jersey
 4       jersey-core
 5       1.18.1
 6     
 7     
 8       com.sun.jersey
 9       jersey-client
10       1.18.1
11     

(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     
2 图片
3 4

(6)结果演示

运行”FileuploadServer”服务器

运行”SpringMVC”服务器

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

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

查看IDEA输出信息

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

三、注意事项

1、传统方式上传文件

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

1     
2     
4         
5         
6     

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

2、跨服务器上传文件

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

此时IEDA输出为

web.xml文件修改处原内容

应修改为

修改后的代码

 1     
 2         default
 3         org.apache.catalina.servlets.DefaultServlet
 4         
 5             debug
 6             0
 7         
 8         
 9             listings
10             false
11         
12         
13             readonly
14             false
15         
16         1
17     

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

四、完整代码

1、pom.xml(SpringMVC)

  1 
  2 
  3 
  5   4.0.0
  6 
  7   org.example
  8   SpringMVC
  9   1.0-SNAPSHOT
 10   war
 11 
 12   SpringMVC Maven Webapp
 13   
 14   http://www.example.com
 15 
 16   
 17     UTF-8
 18     14.0.1
 19     14.0.1
 20     5.0.2.RELEASE
 21   
 22 
 23   
 24   
 25     
 26       org.springframework
 27       spring-context
 28       ${spring.version}
 29     
 30     
 31       org.springframework
 32       spring-web
 33       ${spring.version}
 34     
 35     
 36       org.springframework
 37       spring-webmvc
 38       ${spring.version}
 39     
 40     
 41       javax.servlet
 42       servlet-api
 43       2.5
 44       provided
 45     
 46     
 47       javax.servlet.jsp
 48       jsp-api
 49       2.0
 50       provided
 51     
 52 
 53     
 54     
 55       commons-fileupload
 56       commons-fileupload
 57       1.3.1
 58     
 59     
 60       commons-io
 61       commons-io
 62       2.4
 63     
 64 
 65     
 66     
 67       com.sun.jersey
 68       jersey-core
 69       1.18.1
 70     
 71     
 72       com.sun.jersey
 73       jersey-client
 74       1.18.1
 75     
 76 
 77   
 78 
 79   
 80     SpringMVC
 81     
 82       
 83         
 84           maven-clean-plugin
 85           3.1.0
 86         
 87         
 88         
 89           maven-resources-plugin
 90           3.0.2
 91         
 92         
 93           maven-compiler-plugin
 94           3.8.0
 95         
 96         
 97           maven-surefire-plugin
 98           2.22.1
 99         
100         
101           maven-war-plugin
102           3.2.2
103         
104         
105           maven-install-plugin
106           2.5.2
107         
108         
109           maven-deploy-plugin
110           2.8.2
111         
112       
113     
114   
115 

2、web.xml(SpringMVC)

 1 
 4 
 5 
 6   Archetype Created Web Application
 7 
 8   
 9   
10     characterEncodingFilter
11     org.springframework.web.filter.CharacterEncodingFilter
12     
13       encoding
14       UTF-8
15     
16   
17   
18   characterEncodingFilter
19   /*
20   
21 
22   
23   
24     dispatcherServlet
25     
26     org.springframework.web.servlet.DispatcherServlet
27     
28     
29       contextConfigLocation
30       classpath*:Spring.xml
31     
32     
33     1
34   
35   
36     dispatcherServlet
37     /
38   
39 
40 

3、Spring.xml(SpringMVC)

 1 
 2 
13 
14     
15     
16 
17     
18     
19         
20         
21         
22         
23     
24 
25     
26     
28         
29         
30     
31     
32     
33     
34 

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 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 
 3 
 4     Title
 5 
 6 
 7 
 8     
9 图片
10 11
12 13


14 15
16 图片
17 18
19 20


21 22
23 图片
24 25
26 27 28

6、success.jsp(SpringMVC)

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

跳转成功

9 10 11

7、index.jsp(FileuploadServer)

1 
2 
3 

Hello! FileuploadServer

4 5

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