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. intelliij jdea灰色文件处理办法

  2. html5新属性contenteditable 对于那些不可编辑的标签,现在都可以编辑了

    contenteditable = true 表示该html标签的内容可以编辑,对于那些不可编辑的标签,现在都可以编辑了.

  3. CentOS7.2升级默认yum安装的php版本

    CentOS7.2yum安装php默认版本为5.4,可以升级通过yum安装更高版本 设置yum源 rpm -Uvh https://mirror.webtatic.com/yum/el7/webtat ...

  4. Faster R-CNN论文详解 - CSDN博客

    废话不多说,上车吧,少年 paper链接:Faster R-CNN: Towards Real-Time Object Detection with Region Proposal Networks ...

  5. 洛谷P2024 食物链 [NOI2001] 并查集

    正解:并查集 解题报告: 传送门(咕了! 其实没有很难(虽然我是交了三发才过的QAQ 但是一来好久没打并查集了恢复一下智力 二来看着智推里唯一一个蓝就很不爽(,,,虽然做了这题之后又补上了个蓝题QAQ ...

  6. 前端错误提示whitelabel error page

    1:错误提示whitelabel error page:需要定义一个error.html  ,否则提示如图

  7. [LeetCode] 82. Remove Duplicates from Sorted List II_Medium tag: Linked List

    Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinctnumbe ...

  8. Ubuntu16.04 下创建新用户并赋予sudo权限

    https://blog.csdn.net/wales_2015/article/details/79643336

  9. AISing Programming Contest 2019 Solution

    A - Bulletin Board 签到. #include <bits/stdc++.h> using namespace std; int main() { int n, h, w; ...

  10. ts 绘制多边形

    let bg = this.createBitmapByName("123_png"); this.addChild(bg) bg.x = this.stage.width / 2 ...