用SpringMVC实现的上传下载方式二(多文件上传)
参考来源: 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实现的上传下载方式二(多文件上传)的更多相关文章
- PHP实现文件上传和下载(单文件上传、多文件上传、多个单文件上传)(面向对象、面向过程)
今天我们来学习用PHP进行文件的上传和下载,并且用面向过程和面向对象的方式对文件上传进行一个限制 一.简单的上传测试 1.客户端:upload.php 2.后端:doAction.php 结果: 二. ...
- SpringMVC基础(二)_文件上传、异常处理、拦截器
实现文件上传 实现文件上传,需要借助以下两个第三方 jar 包对上传的二进制文件进行解析: commons-fileupload commons-io form表单的 enctype 取值必须为:mu ...
- JAVA Web 之 struts2文件上传下载演示(二)(转)
JAVA Web 之 struts2文件上传下载演示(二) 一.文件上传演示 详细查看本人的另一篇博客 http://titanseason.iteye.com/blog/1489397 二.文件下载 ...
- ajax方式提交带文件上传的表单,上传后不跳转
ajax方式提交带文件上传的表单 一般的表单都是通过ajax方式提交,所以碰到带文件上传的表单就比较麻烦.基本原理就是在页面增加一个隐藏iframe,然后通过ajax提交除文件之外的表单数据,在表单数 ...
- 十三:SpringBoot-基于Yml配置方式,实现文件上传逻辑
SpringBoot-基于Yml配置方式,实现文件上传逻辑 1.文件上传 2.搭建文件上传界面 2.1 引入页面模板Jar包 2.2 编写简单的上传页面 2.3 配置页面入口 3.SpringBoot ...
- Jquery图片上传组件,支持多文件上传
Jquery图片上传组件,支持多文件上传http://www.jq22.com/jquery-info230jQuery File Upload 是一个Jquery图片上传组件,支持多文件上传.取消. ...
- springMVC两种方式实现多文件上传及效率比较
springMVC实现 多文件上传的方式有两种,一种是我们经常使用的以字节流的方式进行文件上传,另外一种是使用springMVC包装好的解析器进行上传.这两种方式对于实 现多文件上传效率上却有着很大的 ...
- 学习SpringMVC必知必会(7)~springmvc的数据校验、表单标签、文件上传和下载
输入校验是 Web 开发任务之一,在 SpringMVC 中有两种方式可以实现,分别是使用 Spring 自带的验证 框架和使用 JSR 303 实现, 也称之为 spring-validator 和 ...
- Hadoop之HDFS原理及文件上传下载源码分析(上)
HDFS原理 首先说明下,hadoop的各种搭建方式不再介绍,相信各位玩hadoop的同学随便都能搭出来. 楼主的环境: 操作系统:Ubuntu 15.10 hadoop版本:2.7.3 HA:否(随 ...
随机推荐
- P1160 队列安排 洛谷
https://www.luogu.org/problem/show?pid=1160 题目描述 一个学校里老师要将班上N个同学排成一列,同学被编号为1-N,他采取如下的方法: 1.先将1号同学安排进 ...
- cogs——2419. [HZOI 2016]公路修建2
2419. [HZOI 2016]公路修建2 ★☆ 输入文件:hzoi_road2.in 输出文件:hzoi_road2.out 简单对比时间限制:1 s 内存限制:128 MB [题 ...
- springboot整合mybatis连接mysql数据库出现SQLException异常
在springboot整合mybatis连接数据库的时候,项目中遇到一个SQLException,我检查了properties配置文件,看数据源有没有配错,检查有没有打错字,在数据库中把sql语句查询 ...
- linux下crontab安装和使用(定时任务)
在Unix和Linux的操作系统之中,cron可以让系统在指定的时间,去执行某个指定的任务,crontab命令常用于管理对应的cron. 一.crontab在线安装 yum -y install vi ...
- 【cocos2d-x 3.7 飞机大战】 决战南海I (三) 敌机实现
如今来实现敌机类 敌机和我方飞机相似,具有生命值.能够发射子弹.而且有自己的运动轨迹.事实上能够为它们设计一个共同的基类,这样能够更方便扩展. 不同的敌机,应设置不同的标识.属性 // 敌机生命值 c ...
- Linux Centos7 Apache 訪问 You don't have permission to access / on this server.
折腾了非常久,今天才找到了最正确的答案.感言真不easy. 百度出来的99%都是採集的内容.全都是错误的. You don't have permission to access / on this ...
- Node.js创建自签名的HTTPS服务器
https://cnodejs.org/topic/54745ac22804a0997d38b32d 用Node.js创建自签名的HTTPS服务器 发布于 4 年前 作者 eeandrew 6 ...
- 使用Hibernate防止SQL注入的方法
之前写代码,往后台传入一个组织好的String类型的Hql或者Sql语句,去执行. 这样其实是很蠢的一种做法!!!! 举个栗子~~ 我们模仿一下用户登录的场景: 常见的做法是将前台获取到的用户名和密码 ...
- 解决Eclipse alt+/不出来提示的问题
1. 检查windows ——preferences ——java ——editor —— content assist - advanced,在右上方有一行“select the proposal ...
- 【Dairy】2016.10.20 生日记
今天又有人生日耶(朱子鸿)~破壳快乐! 遥犇献歌一曲<就是现在>掌声!!!!!! 开森,呲到了草莓蛋糕,很好呲的.. 然后下去跑步,拿着奶油叉子,往卜卜脸上抹,可惜zks吸引不够(坑队友) ...