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

用到的依赖jar包:

commons-fileupload 1.3.1
commons-io 2.4

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

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>gugua4</groupId>
<artifactId>gugua17</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>gugua17 Maven Webapp</name>
<url>http://maven.apache.org</url> <properties>
<spring.version>4.3.5.RELEASE</spring.version>
</properties> <dependencies> <!-- spring模块库 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
<!-- transaction事务 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency> <!-- Servlet dependencies -->
<!-- servlet(HttpServletRequest,HttpServletResponse) -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency> <!-- Jstl for jsp page -->
<!-- https://mvnrepository.com/artifact/jstl/jstl -->
<dependency>
<groupId>jstl</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> <!-- 文件上传 -->
<!-- Apache Commons FileUpload -->
<!-- https://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>gugua17</finalName>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
</plugin>
</plugins>
</pluginManagement>
</build> </project>

  

web.xml

<web-app>
<display-name>Archetype Created Web Application</display-name> <context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param> <servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet> <servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping> <listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener> </web-app>

  

spring-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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 引入包 -->
<context:component-scan base-package="springmvc"/> <!-- 自动装配 -->
<context:annotation-config/> <!-- 视图 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</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>

  

applicationContext.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"> </beans>

  

jsp:

uploadOneFile.jsp

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<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="do" enctype="multipart/form-data">
upload to file:<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"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>upload multi file</title>
</head>
<body> <h3>upload multi file</h3>
<form method="post" action="do" enctype="multipart/form-data">
upload to file(1):<input type="file" name="file"><br>
upload to file(2):<input type="file" name="file"><br>
upload to file(3):<input type="file" name="file"><br>
upload to file(4):<input type="file" name="file"><br>
upload to file(5):<input type="file" name="file"><br>
<input type="submit" value="upload">
</form> </body>
</html>

  

uploadResult.xml

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>upload result</title>
</head>
<body> <h3>upload files:</h3>
<c:forEach items="${uploadFiles}" var="file">
-${file}<br>
</c:forEach> </body>
</html>

  

controller

MultipartUploadController.java

package springmvc.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
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 MultipartUploadController { @RequestMapping(value="/upload/one", method=RequestMethod.GET)
public String uploadOneFile()
{
return "uploadOneFile";
} @RequestMapping(value="/upload/multi", method=RequestMethod.GET)
public String uploadMultiFile()
{
return "uploadMultiFile";
} @RequestMapping(value="/upload/do", method=RequestMethod.POST)
public String uploadDo(HttpServletRequest request, Model model, @RequestParam("file") MultipartFile[] files)
{
//获取目录/创建路径
String uploadRootPath = request.getServletContext().getRealPath("upload");
System.out.println(uploadRootPath);
//获取路径
File uploadRootDir = new File(uploadRootPath);
if(!uploadRootDir.exists())
{
uploadRootDir.mkdirs();
} //用来存放上传后的路径地址的变量
List<File> uploadFiles = new ArrayList<File>();
for(int i = 0; i < files.length; i++)
{
MultipartFile file = files[i]; //原文件名
String name = file.getOriginalFilename();
System.out.print(name); if(name != null && name.length() > 0)
{
try { //获取文件字节流
byte[] bytes = file.getBytes(); //新文件路径
File serverFile = new File( uploadRootDir.getAbsolutePath() + File.separator + name ); //将文件字节流输出到刚创建的文件上
BufferedOutputStream stream = new BufferedOutputStream( new FileOutputStream( serverFile ) );
stream.write(bytes);
stream.close(); //将文件路径添加到uploadFiles中
uploadFiles.add( serverFile );
System.out.println( serverFile ); } catch (IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
System.out.println("error to file:" + name);
}
} }
model.addAttribute("uploadFiles", uploadFiles);
return "uploadResult"; } }

  

  

Spring MVC文件上传教程 commons-io/commons-uploadfile的更多相关文章

  1. Spring MVC文件上传教程

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

  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 文件上传 & 文件下载

    索引: 开源Spring解决方案--lm.solution 参看代码 GitHub: pom.xml WebConfig.java index.jsp upload.jsp FileUploadCon ...

  8. Spring MVC文件上传处理

    以下示例显示如何在使用Spring Web MVC框架的表单中上传文件和处理.首先使用Eclipse IDE来创建一个WEB工程,实现一个上传文件并保存的功能.并按照以下步骤使用Spring Web ...

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

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

随机推荐

  1. 【ES6】001---module模块------【巷子】

    001.前言 什么是模块化开发?   为了提高代码的复用度,开发人员会按照功能把大量的js代码分成若干文件,这样在多个页面就可以使用同一个文件了.,下面是某个网站的js引用情况 怎么会有这么多js文件 ...

  2. javascript飞机大战-----0010完整版代码

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  3. 170802、Elasticsearch5.2.2 安装问题记录

    使用Elasticsearch5.2.2 必须安装jdk1.8 [elsearch@vm-mysteel-dc-search01 bin]$ java -version java version &q ...

  4. 解决命令行执行shell脚本成功,但crontab执行失败

    实际生产案例 生产机房自建PPTP客户端通过拨号连接到生产机房,但是一旦客户端网络是意外断线再重新拨号 会产生IP冲突,于是写了一个脚本监控PPTP的IP是否有多个(一般冲突以后会生成2个IP) #! ...

  5. Oracle下Insert的介绍

    Insert是插入语句 insert into table(colname1,colname2) values(value1,valu2) 插入无效的会提示失败 数值类型在插入的时候不需要加引号,但是 ...

  6. 获取access_token示例代码

    文档中心--百度AI-百度AI开放平台 http://ai.baidu.com/docs#/NLP-API/top #include <iostream> #include <cur ...

  7. Linux入门之常用命令(15) lsof

    查看磁盘空间: [root@ticketb ~]# df -h Filesystem Size Used Avail Use% Mounted on /dev/sda1 981M 203M 729M ...

  8. 表单(中)-EasyUI Combogrid 组合网格、EasyUI Numberbox 数字框、EasyUI Datebox 日期框、EasyUI Datetimebox 日期时间框、EasyUI Calendar 日历

    EasyUI Combogrid 组合网格 扩展自 $.fn.combo.defaults 和 $.fn.datagrid.defaults.通过 $.fn.combogrid.defaults 重写 ...

  9. 前端页面汉子显示为问号,需修改 linux下面修改mysql 数据库的字符编码为utf8

    设置MySQL数据库编码为UTF-8 登陆后查看数据库当前编码:SHOW VARIABLES LIKE 'char%'; 修改/etc/mysql/my.cnf (默认安装路径下) (标签下没有的添加 ...

  10. 怎样使用CSS设置文字与文字间距距离?

    [文字与文字间距距离,字与字距离间距CSS如何设置?]如果你也遇到W3Cschool用户唐婷大小姐类似的问题不妨也到W3Cschool编程问答进行提问. 对于使用CSS解决字间距的方法W3Cschoo ...