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
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion>
<groupId>com.yiibai</groupId>
<artifactId>SpringMVCFileUpload</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>SpringMVCFileUpload Maven Webapp</name>
<url>http://maven.apache.org</url> <dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency> <!-- Servlet API -->
<!-- http://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency> <!-- Jstl for jsp page -->
<!-- http://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency> <!-- JSP API -->
<!-- http://mvnrepository.com/artifact/javax.servlet.jsp/jsp-api -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency> <!-- Spring dependencies -->
<!-- http://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.4.RELEASE</version>
</dependency> <!-- http://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.4.RELEASE</version>
</dependency> <!-- http://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.4.RELEASE</version>
</dependency> <!-- Apache Commons FileUpload -->
<!-- http://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency> <!-- Apache Commons IO -->
<!-- http://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
</dependencies> <build>
<finalName>SpringMVCFileUpload</finalName>
<plugins> <!-- Config: Maven Tomcat Plugin -->
<!-- http://mvnrepository.com/artifact/org.apache.tomcat.maven/tomcat7-maven-plugin -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version> <!-- Config: contextPath and Port (Default - /SpringMVCFileUpload : 8080) --> <!--
<configuration>
<path>/</path>
<port>8899</port>
</configuration>
-->
</plugin>
</plugins>
</build> </project>

4- 配置Spring

 


配置 web.xml.

SpringContextListener 将读取参数 contextConfigLocation 在配置文件:
  • WEB-INF/web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0"> <display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>spring-mvc</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet> <servlet-mapping>
<servlet-name>spring-mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping> <!-- Other XML Configuration -->
<!-- Load by Spring ContextLoaderListener -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/root-context.xml
</param-value>
</context-param> <!-- Spring ContextLoaderListener -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> </web-app>
配置 Spring MVC:
  • WEB-INF/spring-mvc-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"> <!-- Package Scan -->
<context:component-scan base-package="com.yiibai.springmvcfileupload" /> <!-- Enables the Spring MVC Annotation Configuration -->
<context:annotation-config />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix">
<value>/WEB-INF/pages/</value>
</property> <property name="suffix">
<value>.jsp</value>
</property>
</bean> <bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- Maximum file size: 1MB -->
<!-- 1MB = 125000 Byte -->
<property name="maxUploadSize" value="125000" />
</bean> </beans>
  • WEB-INF/root-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- Empty --> </beans>

5- Java类

  • MyFileUploadController.java
package com.yiibai.springmvcfileupload;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile; @Controller
public class MyFileUploadController { // Upload One File.
@RequestMapping(value = "/uploadOneFile")
public String uploadOneFileHandler() {
// Forward to "/WEB-INF/pages/uploadOneFile.jsp".
return "uploadOneFile";
} // Upload Multi File.
@RequestMapping(value = "/uploadMultiFile")
public String uploadMultiFileHandler() {
// Forward to "/WEB-INF/pages/uploadMultiFile.jsp".
return "uploadMultiFile";
} // uploadOneFile.jsp, uploadMultiFile.jsp submit to.
@RequestMapping(value = "/doUpload", method = RequestMethod.POST)
public String uploadFileHandler(HttpServletRequest request, Model model,
@RequestParam("file") MultipartFile[] files) { // Root Directory.
String uploadRootPath = request.getServletContext().getRealPath(
"upload");
System.out.println("uploadRootPath=" + uploadRootPath); File uploadRootDir = new File(uploadRootPath);
//
// Create directory if it not exists.
if (!uploadRootDir.exists()) {
uploadRootDir.mkdirs();
}
//
List<File> uploadedFiles = new ArrayList<File>();
for (int i = 0; i < files.length; i++) {
MultipartFile file = files[i]; // Client File Name
String name = file.getOriginalFilename();
System.out.println("Client File Name = " + name); if (name != null && name.length() > 0) {
try {
byte[] bytes = file.getBytes(); // Create the file on server
File serverFile = new File(uploadRootDir.getAbsolutePath()
+ File.separator + name); // Stream to write data to file in server.
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
//
uploadedFiles.add(serverFile);
System.out.println("Write file: " + serverFile);
} catch (Exception e) {
System.out.println("Error Write file: " + name);
}
}
}
model.addAttribute("uploadedFiles", uploadedFiles);
return "uploadResult";
} }

6- 视图(JSP)

  • uploadOneFile.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Upload One File</title>
</head>
<body> <h3>Upload One File:</h3> <form method="POST" action="doUpload" enctype="multipart/form-data">
File to upload: <input type="file" name="file"><br />
<input type="submit" value="Upload">
</form> </body>
</html>
  • uploadMultiFile.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Upload Multi File</title>
</head>
<body> <h3>Upload Multiple File:</h3> <form method="POST" action="doUpload" enctype="multipart/form-data"> File to upload (1): <input type="file" name="file"><br />
File to upload (2): <input type="file" name="file"><br />
File to upload (3): <input type="file" name="file"><br />
File to upload (4): <input type="file" name="file"><br />
File to upload (5): <input type="file" name="file"><br /> <input type="submit" value="Upload">
</form>
</body>
</html>
  • uploadResult.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Upload Result</title>
</head>
<body>
<h3>Uploaded Files:</h3> <c:forEach items="${uploadedFiles}" var="file">
- ${file} <br>
</c:forEach> </body>
</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. 数组中的push()和pop()方法

    push()方法可以接受任意数量的参数,把它们逐个添加到数组末尾,并返回修改后数组的长度. pop()方法是从数组末尾移除最后一项,减小数组的length值,然后返回移除的项. var arr = [ ...

  2. touch: cannot touch ‘/var/jenkins_home/copy_reference_file.log’: Permission denied Can not write to /var/jenkins_home/copy_reference_file.log. Wrong volume permissions?

    问题:在从 https://c.163.com/hub#/m/repository/?repoId=3093 下载镜像 docker pull hub.c.163.com/library/jenkin ...

  3. ylbtech-LanguageSamples-CollectionClasses(集合类)

    ylbtech-Microsoft-CSharpSamples:ylbtech-LanguageSamples-CollectionClasses(集合类) 1.A,示例(Sample) 返回顶部 “ ...

  4. [转载]Ubuntu 14.04中root 密码忘记解决方法

      Ubuntu 14.04中root 密码忘记解决方法 方法一: 如果用户具有sudo权限,那么直接可以运行如下命令: #sudo su root #passwd #更改密码 或者直接运行sudo ...

  5. Zabbix的SNMPTrap监控配置

    SNMPTrap监控主要用于设备发生故障时的主动通知的监控.以下简单记录下Zabbix的SNMPTrap的配置方法. 一.SNMPTrap监控的处理流程说明 1.监控对象发送SNMPTrap信息到sn ...

  6. RenderMonkey 练习 第一天 【opengl 纹理】

    础实例: 我们首先实现一个带纹理模型的显示,大体了解RenderMonkey的操作方式. 1. 打开RenderMonkey, 右击WorkSpace的Effect WorkSpace结点,选择Add ...

  7. Java笔记6:多态

    一.多态的分类对象的多态性:动物 x = new 猫();函数的多态性:函数重载.重写 二.多态的体现父类的引用指向了自己的子类对象父类的引用也可以接收自己的对象 三.多态的前提必须是类与类之间只有关 ...

  8. web报表工具FineReport经常使用函数的使用方法总结(日期和时间函数)

    web报表工具FineReport经常使用函数的使用方法总结(日期和时间函数) 说明:凡函数中以日期作为參数因子的,当中日期的形式都必须是yy/mm/dd.并且必须用英文环境下双引號(" & ...

  9. ubuntu cp(copy) command

    e.g. #cp –p –R  /opt/lampp/drv ~/test   Ubuntu_Linux命令:cp(copy)复制文件或目录 功能: 复制文件或目录   www.2cto.com  说 ...

  10. jquery 事件:2

    unbind(type [,data])     //data是要移除的函数 $('#btn').unbind("click"); //移除click $('#btn').unbi ...