Spring MVC 文件上传下载
(1) 导入jar包:ant.jar、commons-fileupload.jar、connom-io.jar。
(2) 在src/context/dispatcher.xml中添加
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:defaultEncoding="UTF-8" />
注意,需要在头部添加内容,添加后如下所示:
<beans default-lazy-init="true"
xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
(3) 添加工具类FileOperateUtil.java
/**
*
* @author geloin
* @date 2012-5-5 下午12:05:57
*/
package com.geloin.spring.util; import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest; /**
*
* @author geloin
* @date 2012-5-5 下午12:05:57
*/
public class FileOperateUtil {
private static final String REALNAME = "realName";
private static final String STORENAME = "storeName";
private static final String SIZE = "size";
private static final String SUFFIX = "suffix";
private static final String CONTENTTYPE = "contentType";
private static final String CREATETIME = "createTime";
private static final String UPLOADDIR = "uploadDir/"; /**
* 将上传的文件进行重命名
*
* @author geloin
* @date 2012-3-29 下午3:39:53
* @param name
* @return
*/
private static String rename(String name) { Long now = Long.parseLong(new SimpleDateFormat("yyyyMMddHHmmss")
.format(new Date()));
Long random = (long) (Math.random() * now);
String fileName = now + "" + random; if (name.indexOf(".") != -1) {
fileName += name.substring(name.lastIndexOf("."));
} return fileName;
} /**
* 压缩后的文件名
*
* @author geloin
* @date 2012-3-29 下午6:21:32
* @param name
* @return
*/
private static String zipName(String name) {
String prefix = "";
if (name.indexOf(".") != -1) {
prefix = name.substring(0, name.lastIndexOf("."));
} else {
prefix = name;
}
return prefix + ".zip";
} /**
* 上传文件
*
* @author geloin
* @date 2012-5-5 下午12:25:47
* @param request
* @param params
* @param values
* @return
* @throws Exception
*/
public static List<Map<String, Object>> upload(HttpServletRequest request,
String[] params, Map<String, Object[]> values) throws Exception { List<Map<String, Object>> result = new ArrayList<Map<String, Object>>(); MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMap = mRequest.getFileMap(); String uploadDir = request.getSession().getServletContext()
.getRealPath("/")
+ FileOperateUtil.UPLOADDIR;
File file = new File(uploadDir); if (!file.exists()) {
file.mkdir();
} String fileName = null;
int i = 0;
for (Iterator<Map.Entry<String, MultipartFile>> it = fileMap.entrySet()
.iterator(); it.hasNext(); i++) { Map.Entry<String, MultipartFile> entry = it.next();
MultipartFile mFile = entry.getValue(); fileName = mFile.getOriginalFilename(); String storeName = rename(fileName); String noZipName = uploadDir + storeName;
String zipName = zipName(noZipName); // 上传成为压缩文件
ZipOutputStream outputStream = new ZipOutputStream(
new BufferedOutputStream(new FileOutputStream(zipName)));
outputStream.putNextEntry(new ZipEntry(fileName));
outputStream.setEncoding("GBK"); FileCopyUtils.copy(mFile.getInputStream(), outputStream); Map<String, Object> map = new HashMap<String, Object>();
// 固定参数值对
map.put(FileOperateUtil.REALNAME, zipName(fileName));
map.put(FileOperateUtil.STORENAME, zipName(storeName));
map.put(FileOperateUtil.SIZE, new File(zipName).length());
map.put(FileOperateUtil.SUFFIX, "zip");
map.put(FileOperateUtil.CONTENTTYPE, "application/octet-stream");
map.put(FileOperateUtil.CREATETIME, new Date()); // 自定义参数值对
for (String param : params) {
map.put(param, values.get(param)[i]);
} result.add(map);
}
return result;
} /**
* 下载
*
* @author geloin
* @date 2012-5-5 下午12:25:39
* @param request
* @param response
* @param storeName
* @param contentType
* @param realName
* @throws Exception
*/
public static void download(HttpServletRequest request,
HttpServletResponse response, String storeName, String contentType,
String realName) throws Exception {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
BufferedInputStream bis = null;
BufferedOutputStream bos = null; String ctxPath = request.getSession().getServletContext()
.getRealPath("/")
+ FileOperateUtil.UPLOADDIR;
String downLoadPath = ctxPath + storeName; long fileLength = new File(downLoadPath).length(); response.setContentType(contentType);
response.setHeader("Content-disposition", "attachment; filename="
+ new String(realName.getBytes("utf-8"), "ISO8859-1"));
response.setHeader("Content-Length", String.valueOf(fileLength)); bis = new BufferedInputStream(new FileInputStream(downLoadPath));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
bis.close();
bos.close();
}
}
可完全使用而不必改变该类,需要注意的是,该类中设定将上传后的文件放置在WebContent/uploadDir下。
(4) 添加FileOperateController.java
/**
*
* @author geloin
* @date 2012-5-5 上午11:56:35
*/
package com.geloin.spring.controller; import java.util.HashMap;
import java.util.List;
import java.util.Map; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView; import com.geloin.spring.util.FileOperateUtil; /**
*
* @author geloin
* @date 2012-5-5 上午11:56:35
*/
@Controller
@RequestMapping(value = "background/fileOperate")
public class FileOperateController {
/**
* 到上传文件的位置
*
* @author geloin
* @date 2012-3-29 下午4:01:31
* @return
*/
@RequestMapping(value = "to_upload")
public ModelAndView toUpload() {
return new ModelAndView("background/fileOperate/upload");
} /**
* 上传文件
*
* @author geloin
* @date 2012-3-29 下午4:01:41
* @param request
* @return
* @throws Exception
*/
@RequestMapping(value = "upload")
public ModelAndView upload(HttpServletRequest request) throws Exception { Map<String, Object> map = new HashMap<String, Object>(); // 别名
String[] alaises = ServletRequestUtils.getStringParameters(request,
"alais"); String[] params = new String[] { "alais" };
Map<String, Object[]> values = new HashMap<String, Object[]>();
values.put("alais", alaises); List<Map<String, Object>> result = FileOperateUtil.upload(request,
params, values); map.put("result", result); return new ModelAndView("background/fileOperate/list", map);
} /**
* 下载
*
* @author geloin
* @date 2012-3-29 下午5:24:14
* @param attachment
* @param request
* @param response
* @return
* @throws Exception
*/
@RequestMapping(value = "download")
public ModelAndView download(HttpServletRequest request,
HttpServletResponse response) throws Exception { String storeName = "201205051340364510870879724.zip";
String realName = "Java设计模式.zip";
String contentType = "application/octet-stream"; FileOperateUtil.download(request, response, storeName, contentType,
realName); return null;
}
}
下载方法请自行变更,若使用数据库保存上传文件的信息时,请参考Spring MVC 整合Mybatis实例。
(5) 添加fileOperate/upload.jsp
<%@ 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 XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Insert title here</title>
</head>
<body>
</body>
<form enctype="multipart/form-data"
action="<c:url value="/background/fileOperate/upload.html" />" method="post">
<input type="file" name="file1" /> <input type="text" name="alais" /><br />
<input type="file" name="file2" /> <input type="text" name="alais" /><br />
<input type="file" name="file3" /> <input type="text" name="alais" /><br />
<input type="submit" value="上传" />
</form>
</html>
确保enctype的值为multipart/form-data;method的值为post。
(6) 添加fileOperate/list.jsp
<%@ 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 XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Insert title here</title>
</head>
<body>
<c:forEach items="${result }" var="item">
<c:forEach items="${item }" var="m">
<c:if test="${m.key eq 'realName' }">
${m.value }
</c:if>
<br />
</c:forEach>
</c:forEach>
</body>
</html>
(7) 通过http://localhost:8080/spring_test/background/fileOperate /to_upload.html访问上传页面,通过http://localhost:8080/spring_test/background /fileOperate/download.html下载文件
Spring MVC 文件上传下载的更多相关文章
- Spring MVC文件上传下载(转载)
原文地址: http://www.cnblogs.com/WJ-163/p/6269409.html 上传参考 http://www.cnblogs.com/lonecloud/p/5990060.h ...
- Spring MVC文件上传下载工具类
import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import ...
- Spring MVC 笔记 —— Spring MVC 文件上传
文件上传 配置MultipartResolver <bean id="multipartResolver" class="org.springframework.w ...
- Spring MVC文件上传教程 commons-io/commons-uploadfile
Spring MVC文件上传教程 commons-io/commons-uploadfile 用到的依赖jar包: commons-fileupload 1.3.1 commons-io 2.4 基于 ...
- 【Java Web开发学习】Spring MVC文件上传
[Java Web开发学习]Spring MVC文件上传 转载:https://www.cnblogs.com/yangchongxing/p/9290489.html 文件上传有两种实现方式,都比较 ...
- Spring mvc文件上传实现
Spring mvc文件上传实现 jsp页面客户端表单编写 三个要素: 1.表单项type="file" 2.表单的提交方式:post 3.表单的enctype属性是多部分表单形式 ...
- Spring MVC 文件上传 & 文件下载
索引: 开源Spring解决方案--lm.solution 参看代码 GitHub: pom.xml WebConfig.java index.jsp upload.jsp FileUploadCon ...
- Spring mvc 文件上传到文件夹(转载+心得)
spring mvc(注解)上传文件的简单例子,这有几个需要注意的地方1.form的enctype=”multipart/form-data” 这个是上传文件必须的2.applicationConte ...
- spring mvc 文件上传 ajax 异步上传
异常代码: 1.the request doesn't contain a multipart/form-data or multipart/mixed stream, content type he ...
随机推荐
- 前端开发必备! 20 个强大的 Sublime Text 插件
http://www.oschina.net/translate/20-powerful-sublimetext-plugins http://www.w3cplus.com/tools/emmet- ...
- [转]AS3复制可视对象
一,复制舞台上的影片剪 方法1——反射方法: var ClassRef:Class = getDefinitionByName(getQualifiedClassName(t_mc)) as Clas ...
- SQL中的循环、for循环、游标
我们使用SQL语句处理数据时,可能会碰到一些需要循环遍历某个表并对其进行相应的操作(添加.修改.删除),这时我们就需要用到咱们在编程中常常用的for或foreach,但是在SQL中写循环往往显得那么吃 ...
- (转)SqlBulkCopy批量复制数据
在.Net1.1中无论是对于批量插入整个DataTable中的所有数据到数据库中,还是进行不同数据源之间的迁移,都不是很方便.而 在.Net2.0中,SQLClient命名空间下增加了几个新类帮助我们 ...
- mysql innodb存储引擎介绍
innodb存储引擎1.存储:数据目录.有配置参数为“ innodb_data_home_dir ” .“ innodb_data_file_path ” 和 “innodb_log_group_ho ...
- NFS配置
一,配置nfs服务端 nfs服务端IP:192.168.1.10 1,安装nfs [root@localhost ~]# yum install -y nfs-utils Loaded plugins ...
- [php-src]一个Php扩展的结构
内容均以php5.6.14为例. 要拥有一个PHP扩展的架子,使用源码中准备好的 /ext/ext_skel 工具,可以生成一个可运行的扩展骨架. 不加选项运行 ./ext_skel,可查看所有可用选 ...
- Browser增加下载路径选择功能
SWE Browser中有xml/download_settings_preferences.xml, 但在代码中却没有调用,导致“设置”中没有”选择下载路径“功能. 在com.android.bro ...
- MSSERVER创建链接服务器
exec sp_addlinkedserver 'DB_RASS','','SQLOLEDB','127.0.0.1' ' exec sp_serveroption 'DB_RASS','rpc ou ...
- java中的继承Object
一个类,要么是直接继承Object,要么就是间接继承Object,如下: class A{ } class B extends A{ } B 是A的子类,A是Object的子类,所以B间接继承了Obj ...