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. Linq初探

    1.什么是LINQ LINQ是语言集成查询(Language Integrated Query),这项技术是在.net 3.5就已经引入的技术,极大的方便了数据的查询,他可以支持数据库.XML.ADO ...

  2. HOJ Recoup Traveling Expenses(最长递减子序列变形)

    A person wants to travel around some places. The welfare in his company can cover some of the airfar ...

  3. 数据去重优化 MemoryError 内存不足

    from ProjectUtil.usingModuleTOMODIFY import getNow export_q_f, q_l, start_ = '/mnt/mongoexport/super ...

  4. I/O排查命令

    I/O可以说是问题大户,线上的问题经常都是它引起的,很多人却不知道怎么定位这种问题.今天简单介绍一下,在此抛砖引玉. 此类问题我们一般分三步定位:按系统级I/O.进程级I/O.业务级I/O定位即可,一 ...

  5. FPN(feature pyramid networks)

    多尺度的object detection算法:FPN(feature pyramid networks). 原来多数的object detection算法都是只采用顶层特征做预测,但我们知道低层的特征 ...

  6. UML Diagrams Using Graphviz Dot

    Introduction Background This article is about using the dot tool from the Graphviz package to automa ...

  7. js基础面试高频面点1:变量提升

    一.什么是变量提升?var变量提升的底层原理是什么? 变量提升的定义:所有变量的声明语句都会被提升到代码头部,这就是变量提升. 原理:引擎在读取js代码的过程中,分为两步,专业来说代码运行是分为预处理 ...

  8. Mysql EXPLAIN 相关疑问: Using temporary ; Using filesort

    一.什么是Using temporary ; Using filesort 1. using filesort filesort主要用于查询数据结果集的排序操作,首先MySQL会使用sort_buff ...

  9. SLAM FOR DUMMIES 第5-8章 中文翻译

    5,SLAM的处理过程 SLAM过程包括许多步骤,该过程的目标是使用环境更新机器人的位置.由于机器人的里程计通常是存在误差的,我们不能直接依赖于里程计.我们可以用激光扫描环境来校正机器人的位置,这是通 ...

  10. Django restframwork获取列表详情

    z哎Django restframwork中就有一个类可以获取列表的详情内容,只有两行代码就可以搞定,在浏览器测试是ok的.但是这样的接口给前端,前端点击详情然后会将models.表名.objects ...