用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>

 

  

  

  

上一篇:Git正确的协作方式(很简单)


下一篇:转:[gevent源码分析] 深度分析gevent运行流程