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
*/
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;
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/";
/**
* 将上传的文件进行重命名
*
* @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;
}
/**
* 压缩后的文件名
*
* @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";
}
/**
* 上传文件
*
* @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;
}
/**
* 下载
* @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
*/
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;
@Controller
@RequestMapping(value = "background/fileOperate")
public class FileOperateController {
/**
* 到上传文件的位置
* @return
*/
@RequestMapping(value = "to_upload")
public ModelAndView toUpload() {
return new ModelAndView("background/fileOperate/upload");
}
/**
* 上传文件
*
* @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);
}
/**
* 下载
*
* @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下载文件
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
# springmvc上传下载
# spring
# mvc上传和下载
# springmvc实现上传
# SpringMVC实现文件的上传和下载实例代码
# springMVC配置环境实现文件上传和下载
# SpringMVC下实现Excel文件上传下载
# SpringMVC实现文件上传和下载功能
# Spring MVC的文件上传和下载以及拦截器的使用实例
# SpringMVC实现文件上传和下载的工具类
# spring mvc实现文件上传与下载功能
# SpringMVC实现文件上传下载的全过程
# 上传
# 上传文件
# 值为
# 的是
# 自定义
# 所示
# 需要注意
# 请参考
# 大家多多
# 压缩文件
# 下载方法
# 重命名
# 类中
# 而不必
# 请自行
# CONTENTTYPE
# String
# REALNAME
# private
# static
相关文章:
如何在建站之星绑定自定义域名?
学校免费自助建站系统:智能生成+拖拽设计+多端适配
建站OpenVZ教程与优化策略:配置指南与性能提升
如何用搬瓦工VPS快速搭建个人网站?
c++怎么用jemalloc c++替换默认内存分配器【性能】
外贸公司网站制作哪家好,maersk船公司官网?
建站之星如何快速更换网站模板?
微信h5制作网站有哪些,免费微信H5页面制作工具?
济南企业网站制作公司,济南社保单位网上缴费步骤?
如何零基础在云服务器搭建WordPress站点?
建站之星代理如何获取技术支持?
网站代码制作软件有哪些,如何生成自己网站的代码?
建站与域名管理如何高效结合?
如何选择服务器才能高效搭建专属网站?
如何打造高效商业网站?建站目的决定转化率
上海制作企业网站有哪些,上海有哪些网站可以让企业免费发布招聘信息?
如何在万网自助建站中设置域名及备案?
JS中使用new Date(str)创建时间对象不兼容firefox和ie的解决方法(两种)
宝塔建站后网页无法访问如何解决?
如何快速查询域名建站关键信息?
如何用已有域名快速搭建网站?
黑客如何通过漏洞一步步攻陷网站服务器?
建站之星如何实现五合一智能建站与营销推广?
电商网站制作价格怎么算,网上拍卖流程以及规则?
高端建站如何打造兼具美学与转化的品牌官网?
Swift中循环语句中的转移语句 break 和 continue
娃派WAP自助建站:免费模板+移动优化,快速打造专业网站
大学网站设计制作软件有哪些,如何将网站制作成自己app?
盐城做公司网站,江苏电子版退休证办理流程?
建站主机类型有哪些?如何正确选型
三星网站视频制作教程下载,三星w23网页如何全屏?
潍坊网站制作公司有哪些,潍坊哪家招聘网站好?
建站ABC备案流程中有哪些关键注意事项?
微信小程序制作网站有哪些,微信小程序需要做网站吗?
建站之星好吗?新手能否轻松上手建站?
官网网站制作腾讯审核要多久,联想路由器newifi官网
网站制作外包价格怎么算,招聘网站上写的“外包”是什么意思?
北京企业网站设计制作公司,北京铁路集团官方网站?
装修招标网站设计制作流程,装修招标流程?
Android使用GridView实现日历的简单功能
自助网站制作软件,个人如何自助建网站?
,制作一个手机app网站要多少钱?
在线教育网站制作平台,山西立德教育官网?
如何快速上传自定义模板至建站之星?
如何在万网自助建站平台快速创建网站?
如何快速搭建高效WAP手机网站?
如何在阿里云香港服务器快速搭建网站?
如何快速重置建站主机并恢复默认配置?
如何通过建站之星自助学习解决操作问题?
公司网站制作需要多少钱,找人做公司网站需要多少钱?
*请认真填写需求信息,我们会在24小时内与您取得联系。