参考来源:      http://blog.csdn.net/qq_32953079/article/details/52290208

1、导入相关jar包

commons-fileupload.jar

commons-io.jar

2、配置web.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>SpringMVC_fileUpLoad</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list> <filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping> </web-app>

3、编写上传页面

<%@ 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>Insert title here</title>
</head>
<body>
<h1>多文件上传</h1>
<form action="upload.action" method="post"enctype="multipart/form-data">
<input type="file" name="pic" /><br/>
<input type="file" name="pic" /><br/>
<input type="file" name="pic" /><br/>
<input type="file" name="pic" /><br/>
<input type="submit" value="上传" />
</form>
</body>
</html>

4、配置springmvc-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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> <context:component-scan base-package="com.etc"></context:component-scan> <bean id="fileUpLoadController" class="com.etc.fileupload.FileUpLoadController"/> <!-- 文件上传的配置 CommonsMultipartResolver公共上传解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 指定所上传文件的总大小不能超过200KB。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->
<!-- <property name="maxUploadSize" value="200000"/> 出错原因1:图片大小限制-->
<property name="maxUploadSize" value="10240000"/>
</bean> <!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 -->
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到WebContent目录下的error.jsp页面 -->
<prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">error.jsp</prop>
</props>
</property>
</bean>
</beans>

5、编写handler处理器

package com.etc.fileupload;
/**
* 上传和下载的区别:
* 上传是将文件上传到服务器中,而下载是将服务器中的文件下载到本地环境中
*
* 回去后,用自己电脑作为服务器,其他电脑作为用户电脑,在尝试一下连接
* 查看上传到服务端的地址以及下载时客户端的地址,
* request.getServletContext().getRealPath("/img")貌似是请求的客户端地址,回去在研究下
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile; @Controller
public class FileUpLoadController { /**
* 多文件上传
* @param pic
* @param model
* @param request
* @return
* @throws IOException
*/
@RequestMapping("/upload.action")
public String UpLoad(@RequestParam MultipartFile[] pic,Model model,HttpServletRequest request) throws IOException{
System.out.println("upload.action进来了!");
List<String> list=new ArrayList<String>();
for(MultipartFile file:pic){
//此处MultipartFile[]表明是多文件,如果是单文件MultipartFile就行了
if(pic==null||file.isEmpty()){
System.out.println("文件未上传!");
}else{
//得到上传的文件名
String filename=file.getOriginalFilename();
System.out.println("文件名: "+filename);
//得到服务器项目发布运行所在地址 //出错问题二:请求地址时,要看是什么层次的请求,request和session是不同的
String pmpath =request.getServletContext().getRealPath("/img")+File.separator;
//String pmpath=request.getServletContext().getRealPath("/img")+ File.separator + filename;
System.out.println("服务器项目发布所在地址: "+pmpath); //此处未使用UUID来生成唯一标识(这也是正常下载的图片是很多数字命名的原因),用日期做为标识 (过会做一下)
String path = pmpath + filename; /*new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+*/
//String path = UUID.randomUUID().toString();
////查看文件上传路径,方便查找
System.out.println("完整的文件上传后,保存所在的路径: "+path);
//将每一个文件名保存到list集合中
list.add(filename);
//list.add(path); //把文件上传至path的路径
File localFile=new File(path);
file.transferTo(localFile);
}
}
model.addAttribute("filenameList",list);
return "uploadSuccess.jsp";
} /**
* 文件下载实现方式一
* @param r
* @param filename
* @return
* @throws IOException
*/
@RequestMapping("/down.action")
public ResponseEntity<byte[]> downFile(HttpServletRequest r,String filename) throws IOException{
//配置http请求头文件信息 HttpHeaders headers = new HttpHeaders();
String path=r.getServletContext().getRealPath("/img")+ File.separator + filename; File file=new File(path); headers.setContentDispositionFormData("attachment",filename);//不自动打开
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); //头文件内容类型
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
headers, HttpStatus.CREATED);
}
/**
* 文件下载实现方式二
* @param fileName
* @param request
* @param response
* @return
*/
@RequestMapping("/download2.action")
public String download(String fileName, HttpServletRequest request,
HttpServletResponse response) {
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName="
+ fileName);
try {
String path = request.getSession().getServletContext().getRealPath
("image")+File.separator;
InputStream inputStream = new FileInputStream(new File(path
+ fileName)); OutputStream os = response.getOutputStream();
byte[] b = new byte[2048];
int length;
while ((length = inputStream.read(b)) > 0) {
os.write(b, 0, length);
}
// 这里主要关闭。
os.close(); inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 返回值要注意,要不然就出现下面这句错误!
//java+getOutputStream() has already been called for this response
return null;
}
}

6、编写下载页面

<%@ 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>Insert title here</title>
<style>
div{
float: left;
} </style>
</head>
<body>
<h1>图片上传成功</h1>
<!-- 图片显示问题解决,服务器上不能写绝对地址,也不能加/img这种格式,应该是img/这种格式,看看图片重复怎么解决-->
<div style="width:600px">
<c:forEach items="${filenameList}" var="fname">
<div style="width:200px">
<img src="img/${fname}" width="200px"/>
</div>
</c:forEach>
</div>
<%-- <a href="down.action?filename=${filename}">下载</a> --%>
</body>
</html>

 

  

  

  

用SpringMVC实现的上传下载方式二(多文件上传)的更多相关文章

  1. PHP实现文件上传和下载(单文件上传、多文件上传、多个单文件上传)(面向对象、面向过程)

    今天我们来学习用PHP进行文件的上传和下载,并且用面向过程和面向对象的方式对文件上传进行一个限制 一.简单的上传测试 1.客户端:upload.php 2.后端:doAction.php 结果: 二. ...

  2. SpringMVC基础(二)_文件上传、异常处理、拦截器

    实现文件上传 实现文件上传,需要借助以下两个第三方 jar 包对上传的二进制文件进行解析: commons-fileupload commons-io form表单的 enctype 取值必须为:mu ...

  3. JAVA Web 之 struts2文件上传下载演示(二)(转)

    JAVA Web 之 struts2文件上传下载演示(二) 一.文件上传演示 详细查看本人的另一篇博客 http://titanseason.iteye.com/blog/1489397 二.文件下载 ...

  4. ajax方式提交带文件上传的表单,上传后不跳转

    ajax方式提交带文件上传的表单 一般的表单都是通过ajax方式提交,所以碰到带文件上传的表单就比较麻烦.基本原理就是在页面增加一个隐藏iframe,然后通过ajax提交除文件之外的表单数据,在表单数 ...

  5. 十三:SpringBoot-基于Yml配置方式,实现文件上传逻辑

    SpringBoot-基于Yml配置方式,实现文件上传逻辑 1.文件上传 2.搭建文件上传界面 2.1 引入页面模板Jar包 2.2 编写简单的上传页面 2.3 配置页面入口 3.SpringBoot ...

  6. Jquery图片上传组件,支持多文件上传

    Jquery图片上传组件,支持多文件上传http://www.jq22.com/jquery-info230jQuery File Upload 是一个Jquery图片上传组件,支持多文件上传.取消. ...

  7. springMVC两种方式实现多文件上传及效率比较

    springMVC实现 多文件上传的方式有两种,一种是我们经常使用的以字节流的方式进行文件上传,另外一种是使用springMVC包装好的解析器进行上传.这两种方式对于实 现多文件上传效率上却有着很大的 ...

  8. 学习SpringMVC必知必会(7)~springmvc的数据校验、表单标签、文件上传和下载

    输入校验是 Web 开发任务之一,在 SpringMVC 中有两种方式可以实现,分别是使用 Spring 自带的验证 框架和使用 JSR 303 实现, 也称之为 spring-validator 和 ...

  9. Hadoop之HDFS原理及文件上传下载源码分析(上)

    HDFS原理 首先说明下,hadoop的各种搭建方式不再介绍,相信各位玩hadoop的同学随便都能搭出来. 楼主的环境: 操作系统:Ubuntu 15.10 hadoop版本:2.7.3 HA:否(随 ...

随机推荐

  1. mysql控制流程函数(case,if,ifnull,nullif)

    1.case...when... 用法 参考:http://www.cnblogs.com/qlqwjy/p/7476533.html CASE value WHEN [compare-value] ...

  2. Oracle中,利用sql语句中的函数实现保留两位小数和四舍五入保留两位小数

    Oracle中,利用sql语句中的函数实现保留两位小数和四舍五入保留两位小数: select trunc(1.23856789,2) from dual round(m,n) 可以四舍五入 trunc ...

  3. openstack setup demo Enviroment

    Enviroment 本文包含以下部分. Host networking Network Time Protocol (NTP) OpenStack packages SQL database NoS ...

  4. epoll 的accept , read, write

    http://www.ccvita.com/515.html 在一个非阻塞(fcntl)的socket上调用read/write函数, 返回EAGAIN或者EWOULDBLOCK(注: EAGAIN就 ...

  5. Brackets常用插件

    Emmet插件:https://github.com/emmetio/brackets-emmet AngularJS插件:https://github.com/angular-ui/AngularJ ...

  6. https://security.stackexchange.com/questions/68405/what-is-tmunblock-cgi-and-can-it-be-exploited-by-shellshock-linux-apache-w

    hndUnblock.cgi   Line #1124 : 187.38.233.45 - - [15/Jan/2018:21:36:45 +0800] "GET /hndUnblock.c ...

  7. openstack horizon 学习(2) navigation、dashboard、panels

    本章的主要内容是如何用horizon的navigation结构添加一个应用的面板. Horizon中提供了两种为应用添加panel的方法,一种是通过Pluggable Settings的方式,另一种是 ...

  8. Linux 常用命令大全2

    Linux 常用命令大全 [帮助命令] command —help man command man 2 command 查看第2个帮助文件 man -k keyword 查找含有关键字的帮助 info ...

  9. python 统计文件的个数

    import os path = r'F:\1back\picture' #获取当前路径 count = 0 for root,dirs,files in os.walk(path): #遍历统计 i ...

  10. CMake使用总结

    总结CMake的常用命令,并介绍有用的CMake资源. CMake意为cross-platform make,可用于管理c/c++工程.CMake解析配置文件CMakeLists.txt生成Makef ...