1- 介绍

这篇教程文章是基于 Spring MVC来实现文件的上传功能,这里主要是实现两个功能:1、上传单个文件并将其移动到对应的上传目录;2、一次上传多个文件并将它们存储在指定文件夹下,接下来我们一步步地实现。

2- 创建工程

  • File/New/Other..


输入:

  • Group ID: com.yiibai
  • Artifact ID: SpringMVCFileUpload
  • Package: com.yiibai.springmvcfileupload


这样,工程就被创建了,如下图所示:

 

不要担心项目被创建时有错误消息。原因是,你还没有声明的Servlet库。

注意:

Eclipse 4.4 (Luna) 创建 Maven 项目结构可能会有错误,需要修复它。
 

3- 配置Maven

  • pom.xml
  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  3.  
  4. <modelVersion>4.0.0</modelVersion>
  5. <groupId>com.yiibai</groupId>
  6. <artifactId>SpringMVCFileUpload</artifactId>
  7. <packaging>war</packaging>
  8. <version>0.0.1-SNAPSHOT</version>
  9. <name>SpringMVCFileUpload Maven Webapp</name>
  10. <url>http://maven.apache.org</url>
  11.  
  12. <dependencies>
  13. <dependency>
  14. <groupId>junit</groupId>
  15. <artifactId>junit</artifactId>
  16. <version>3.8.1</version>
  17. <scope>test</scope>
  18. </dependency>
  19.  
  20. <!-- Servlet API -->
  21. <!-- http://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
  22. <dependency>
  23. <groupId>javax.servlet</groupId>
  24. <artifactId>javax.servlet-api</artifactId>
  25. <version>3.1.0</version>
  26. <scope>provided</scope>
  27. </dependency>
  28.  
  29. <!-- Jstl for jsp page -->
  30. <!-- http://mvnrepository.com/artifact/javax.servlet/jstl -->
  31. <dependency>
  32. <groupId>javax.servlet</groupId>
  33. <artifactId>jstl</artifactId>
  34. <version>1.2</version>
  35. </dependency>
  36.  
  37. <!-- JSP API -->
  38. <!-- http://mvnrepository.com/artifact/javax.servlet.jsp/jsp-api -->
  39. <dependency>
  40. <groupId>javax.servlet.jsp</groupId>
  41. <artifactId>jsp-api</artifactId>
  42. <version>2.2</version>
  43. <scope>provided</scope>
  44. </dependency>
  45.  
  46. <!-- Spring dependencies -->
  47. <!-- http://mvnrepository.com/artifact/org.springframework/spring-core -->
  48. <dependency>
  49. <groupId>org.springframework</groupId>
  50. <artifactId>spring-core</artifactId>
  51. <version>4.1.4.RELEASE</version>
  52. </dependency>
  53.  
  54. <!-- http://mvnrepository.com/artifact/org.springframework/spring-web -->
  55. <dependency>
  56. <groupId>org.springframework</groupId>
  57. <artifactId>spring-web</artifactId>
  58. <version>4.1.4.RELEASE</version>
  59. </dependency>
  60.  
  61. <!-- http://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
  62. <dependency>
  63. <groupId>org.springframework</groupId>
  64. <artifactId>spring-webmvc</artifactId>
  65. <version>4.1.4.RELEASE</version>
  66. </dependency>
  67.  
  68. <!-- Apache Commons FileUpload -->
  69. <!-- http://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
  70. <dependency>
  71. <groupId>commons-fileupload</groupId>
  72. <artifactId>commons-fileupload</artifactId>
  73. <version>1.3.1</version>
  74. </dependency>
  75.  
  76. <!-- Apache Commons IO -->
  77. <!-- http://mvnrepository.com/artifact/commons-io/commons-io -->
  78. <dependency>
  79. <groupId>commons-io</groupId>
  80. <artifactId>commons-io</artifactId>
  81. <version>2.4</version>
  82. </dependency>
  83. </dependencies>
  84.  
  85. <build>
  86. <finalName>SpringMVCFileUpload</finalName>
  87. <plugins>
  88.  
  89. <!-- Config: Maven Tomcat Plugin -->
  90. <!-- http://mvnrepository.com/artifact/org.apache.tomcat.maven/tomcat7-maven-plugin -->
  91. <plugin>
  92. <groupId>org.apache.tomcat.maven</groupId>
  93. <artifactId>tomcat7-maven-plugin</artifactId>
  94. <version>2.2</version>
  95.  
  96. <!-- Config: contextPath and Port (Default - /SpringMVCFileUpload : 8080) -->
  97.  
  98. <!--
  99. <configuration>
  100. <path>/</path>
  101. <port>8899</port>
  102. </configuration>
  103. -->
  104. </plugin>
  105. </plugins>
  106. </build>
  107.  
  108. </project>

4- 配置Spring

 


配置 web.xml.

SpringContextListener 将读取参数 contextConfigLocation 在配置文件:
  • WEB-INF/web.xml
  1. <web-app xmlns="http://java.sun.com/xml/ns/javaee"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
  4. http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  5. version="3.0">
  6.  
  7. <display-name>Archetype Created Web Application</display-name>
  8. <servlet>
  9. <servlet-name>spring-mvc</servlet-name>
  10. <servlet-class>
  11. org.springframework.web.servlet.DispatcherServlet
  12. </servlet-class>
  13. <load-on-startup>1</load-on-startup>
  14. </servlet>
  15.  
  16. <servlet-mapping>
  17. <servlet-name>spring-mvc</servlet-name>
  18. <url-pattern>/</url-pattern>
  19. </servlet-mapping>
  20.  
  21. <!-- Other XML Configuration -->
  22. <!-- Load by Spring ContextLoaderListener -->
  23. <context-param>
  24. <param-name>contextConfigLocation</param-name>
  25. <param-value>
  26. /WEB-INF/root-context.xml
  27. </param-value>
  28. </context-param>
  29.  
  30. <!-- Spring ContextLoaderListener -->
  31. <listener>
  32. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  33. </listener>
  34.  
  35. </web-app>
配置 Spring MVC:
  • WEB-INF/spring-mvc-servlet.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. xmlns:p="http://www.springframework.org/schema/p"
  5. xmlns:context="http://www.springframework.org/schema/context"
  6. xmlns:mvc="http://www.springframework.org/schema/mvc"
  7. xsi:schemaLocation="http://www.springframework.org/schema/beans
  8. http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
  9. http://www.springframework.org/schema/context
  10. http://www.springframework.org/schema/context/spring-context-4.1.xsd
  11. http://www.springframework.org/schema/mvc
  12. http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
  13.  
  14. <!-- Package Scan -->
  15. <context:component-scan base-package="com.yiibai.springmvcfileupload" />
  16.  
  17. <!-- Enables the Spring MVC Annotation Configuration -->
  18. <context:annotation-config />
  19. <bean
  20. class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  21.  
  22. <property name="prefix">
  23. <value>/WEB-INF/pages/</value>
  24. </property>
  25.  
  26. <property name="suffix">
  27. <value>.jsp</value>
  28. </property>
  29. </bean>
  30.  
  31. <bean id="multipartResolver"
  32. class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  33.  
  34. <!-- Maximum file size: 1MB -->
  35. <!-- 1MB = 125000 Byte -->
  36. <property name="maxUploadSize" value="125000" />
  37. </bean>
  38.  
  39. </beans>
  • WEB-INF/root-context.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
  5. http://www.springframework.org/schema/beans/spring-beans.xsd">
  6.  
  7. <!-- Empty -->
  8.  
  9. </beans>

5- Java类

  • MyFileUploadController.java
  1. package com.yiibai.springmvcfileupload;
  2.  
  3. import java.io.BufferedOutputStream;
  4. import java.io.File;
  5. import java.io.FileOutputStream;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8.  
  9. import javax.servlet.http.HttpServletRequest;
  10.  
  11. import org.springframework.stereotype.Controller;
  12. import org.springframework.ui.Model;
  13. import org.springframework.web.bind.annotation.RequestMapping;
  14. import org.springframework.web.bind.annotation.RequestMethod;
  15. import org.springframework.web.bind.annotation.RequestParam;
  16. import org.springframework.web.multipart.MultipartFile;
  17.  
  18. @Controller
  19. public class MyFileUploadController {
  20.  
  21. // Upload One File.
  22. @RequestMapping(value = "/uploadOneFile")
  23. public String uploadOneFileHandler() {
  24. // Forward to "/WEB-INF/pages/uploadOneFile.jsp".
  25. return "uploadOneFile";
  26. }
  27.  
  28. // Upload Multi File.
  29. @RequestMapping(value = "/uploadMultiFile")
  30. public String uploadMultiFileHandler() {
  31. // Forward to "/WEB-INF/pages/uploadMultiFile.jsp".
  32. return "uploadMultiFile";
  33. }
  34.  
  35. // uploadOneFile.jsp, uploadMultiFile.jsp submit to.
  36. @RequestMapping(value = "/doUpload", method = RequestMethod.POST)
  37. public String uploadFileHandler(HttpServletRequest request, Model model,
  38. @RequestParam("file") MultipartFile[] files) {
  39.  
  40. // Root Directory.
  41. String uploadRootPath = request.getServletContext().getRealPath(
  42. "upload");
  43. System.out.println("uploadRootPath=" + uploadRootPath);
  44.  
  45. File uploadRootDir = new File(uploadRootPath);
  46. //
  47. // Create directory if it not exists.
  48. if (!uploadRootDir.exists()) {
  49. uploadRootDir.mkdirs();
  50. }
  51. //
  52. List<File> uploadedFiles = new ArrayList<File>();
  53. for (int i = 0; i < files.length; i++) {
  54. MultipartFile file = files[i];
  55.  
  56. // Client File Name
  57. String name = file.getOriginalFilename();
  58. System.out.println("Client File Name = " + name);
  59.  
  60. if (name != null && name.length() > 0) {
  61. try {
  62. byte[] bytes = file.getBytes();
  63.  
  64. // Create the file on server
  65. File serverFile = new File(uploadRootDir.getAbsolutePath()
  66. + File.separator + name);
  67.  
  68. // Stream to write data to file in server.
  69. BufferedOutputStream stream = new BufferedOutputStream(
  70. new FileOutputStream(serverFile));
  71. stream.write(bytes);
  72. stream.close();
  73. //
  74. uploadedFiles.add(serverFile);
  75. System.out.println("Write file: " + serverFile);
  76. } catch (Exception e) {
  77. System.out.println("Error Write file: " + name);
  78. }
  79. }
  80. }
  81. model.addAttribute("uploadedFiles", uploadedFiles);
  82. return "uploadResult";
  83. }
  84.  
  85. }

6- 视图(JSP)

  • uploadOneFile.jsp
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding="UTF-8"%>
  3. <html>
  4. <head>
  5. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  6. <title>Upload One File</title>
  7. </head>
  8. <body>
  9.  
  10. <h3>Upload One File:</h3>
  11.  
  12. <form method="POST" action="doUpload" enctype="multipart/form-data">
  13. File to upload: <input type="file" name="file"><br />
  14. <input type="submit" value="Upload">
  15. </form>
  16.  
  17. </body>
  18. </html>
  • uploadMultiFile.jsp
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding="UTF-8"%>
  3. <html>
  4. <head>
  5. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  6. <title>Upload Multi File</title>
  7. </head>
  8. <body>
  9.  
  10. <h3>Upload Multiple File:</h3>
  11.  
  12. <form method="POST" action="doUpload" enctype="multipart/form-data">
  13.  
  14. File to upload (1): <input type="file" name="file"><br />
  15. File to upload (2): <input type="file" name="file"><br />
  16. File to upload (3): <input type="file" name="file"><br />
  17. File to upload (4): <input type="file" name="file"><br />
  18. File to upload (5): <input type="file" name="file"><br />
  19.  
  20. <input type="submit" value="Upload">
  21. </form>
  22. </body>
  23. </html>
  • uploadResult.jsp
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding="UTF-8"%>
  3.  
  4. <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
  5.  
  6. <html>
  7. <head>
  8. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  9. <title>Upload Result</title>
  10. </head>
  11. <body>
  12. <h3>Uploaded Files:</h3>
  13.  
  14. <c:forEach items="${uploadedFiles}" var="file">
  15. - ${file} <br>
  16. </c:forEach>
  17.  
  18. </body>
  19. </html>

7- 运行应用程序

首先,运行应用程序之前,你需要构建整个项目。
右键单击该项目并选择:

 
运行配置:
 

输入:
  • Name: Run SpringMVCFileUpload
  • Base directory: ${workspace_loc:/SpringMVCFileUpload}
  • Goals: tomcat7:run



点击运行(Run):

  • http://localhost:8080/SpringMVCFileUpload/uploadOneFile


  • http://localhost:8080/SpringMVCFileUpload/uploadMultiFile

    a

Spring MVC文件上传教程的更多相关文章

  1. Spring MVC文件上传教程 commons-io/commons-uploadfile

    Spring MVC文件上传教程 commons-io/commons-uploadfile 用到的依赖jar包: commons-fileupload 1.3.1 commons-io 2.4 基于 ...

  2. Spring MVC 笔记 —— Spring MVC 文件上传

    文件上传 配置MultipartResolver <bean id="multipartResolver" class="org.springframework.w ...

  3. 【Java Web开发学习】Spring MVC文件上传

    [Java Web开发学习]Spring MVC文件上传 转载:https://www.cnblogs.com/yangchongxing/p/9290489.html 文件上传有两种实现方式,都比较 ...

  4. Spring mvc文件上传实现

    Spring mvc文件上传实现 jsp页面客户端表单编写 三个要素: 1.表单项type="file" 2.表单的提交方式:post 3.表单的enctype属性是多部分表单形式 ...

  5. Spring mvc 文件上传到文件夹(转载+心得)

    spring mvc(注解)上传文件的简单例子,这有几个需要注意的地方1.form的enctype=”multipart/form-data” 这个是上传文件必须的2.applicationConte ...

  6. spring mvc 文件上传 ajax 异步上传

    异常代码: 1.the request doesn't contain a multipart/form-data or multipart/mixed stream, content type he ...

  7. Spring MVC文件上传出现错误:Required MultipartFile parameter 'file' is not present

    1.配置文件上传的解析器 首先需要在spring mvc的配置文件中(注意是spring mvc的配置文件而不是spring的配置文件:applicationContext.xml)配置: sprin ...

  8. spring mvc文件上传(单个文件上传|多个文件上传)

    单个文件上传spring mvc 实现文件上传需要引入两个必须的jar包    1.所需jar包:                commons-fileupload-1.3.1.jar       ...

  9. Strut2 和Spring MVC 文件上传对比

    在Java领域中,有两个常用的文件上传项目:一个是Apache组织Jakarta的Common-FileUpload组件 (http://commons.apache.org/proper/commo ...

随机推荐

  1. ylbtech-LanguageSamples-ExplicitInterface(显示接口)

    ylbtech-Microsoft-CSharpSamples:ylbtech-LanguageSamples-ExplicitInterface(显示接口) 1.A,示例(Sample) 返回顶部 ...

  2. jsp标签、 项目全路径引用${ctx}

    请根据自己的需要选择以下标签. <%@ taglib uri="/struts-tags" prefix="s"%> <%@ taglib u ...

  3. Oracle中分页查询语句的写法

    要动态的变化分页查询的条件,比如pageNow 这个变量表示的是当前是第几页, oracle分页有通用写法,假设一页5行 select * from ( select t.*,rownum rn fr ...

  4. What is Continuous Integration?

    什么叫持续集成? 原文: https://docs.microsoft.com/en-us/azure/devops/what-is-continuous-integration ---------- ...

  5. zStack学习笔记(原创,绝对不是抄的……)

    我之前写的文章都没写上面那句,但是这篇写了,主要是因为zStack文章抄袭太严重……故此声明 因为涉及到数据的双向交互问题,所以在这里我考虑使用协议栈来实现数据的收发.首先说下如何在Zstack中添加 ...

  6. Windows COM Surrogate 已停止工作怎么办

    已解决 如何解决"COM Surrogate 已停止工作"问题 悬赏分:15 - 解决时间:2008-7-6 16:55 Vista系统,经常出现这个提示框,烦人. 我试了网上有关 ...

  7. zoj How Many Sets I(组合计数)

    http://acm.zju.edu.cn/onlinejudge/showProblem.do? problemId=4535 一个集合s有n个元素,求满足这种集合序列{s1,s2....sk}使S ...

  8. 初次玩耍lucene.net,一个小小的记录

    lucene.net虽说是强大,但是我还是一年前第一次玩耍,然后就没有然后了,最近准备养成记录博客的习惯了,所以又玩了玩,回来记录一下 首先新建一个类,便于调用 public class Lucene ...

  9. 一种在MVC3框架里面设置模板页的方法,不使用_ViewStart

    1.新建MasterFilterAttribute类继承ActionFilterAttribute,重写方法OnActionExecuted ,指定ViewResult的MasterName = &q ...

  10. Mysql命令行备份与还原数据库操作实例

    无论是Windows还是Linux,都可以通过如下命令行形式备份Mysql数据库 备份命令: 在windows的DOS窗口命令行或linux的shell命令行,假设需要备份的数据库是advanced: ...