springMVC上传下载
来源:互联网 发布:梦幻西游总是网络错误 编辑:程序博客网 时间:2024/06/16 18:26
本文基于Spring MVC 注解,让Spring跑起来。
(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下载文件
我自己写的文件上传:
@RequiresPermissions("oa:audition:edit")
@RequestMapping("/save")
public String save(Audition audition,Model model,MultipartFile upload,HttpServletRequest request) throws IOException {
if(upload!=null){
String realPath = request.getSession().getServletContext().getRealPath("/WEB-INF/upload");
FileUtils.copyInputStreamToFile(upload.getInputStream(), new File(realPath, upload.getOriginalFilename()));
String p=audition.getAnnuxPath();
String filePath=realPath+"\\"+p;
audition.setAnnuxPath(filePath);
auditionService.save(audition);
model.addAttribute("message","保存成功");
model.addAttribute("audition",audition);
}
return "modules/oa/auditionForm";
}
@RequestMapping("/checkFileName")
public void checkFileName(String fileName,HttpServletRequest request,HttpServletResponse response) throws IOException {
File[] files=getFiles(request, response);
PrintWriter out=response.getWriter();
for(int i=0;i<files.length;i++){
if((files[i].getName()).equals(fileName)){
out.write("true");
break;
}
out.write("false");
}
}
//获取指定路径下的所有文件组成的集合
public File[] getFiles(HttpServletRequest request,HttpServletResponse response) throws IOException {
String realPath = request.getSession().getServletContext().getRealPath("/WEB-INF/upload");
File dir=new File(realPath);
File[] files=dir.listFiles();
return files;
}
下载:
@RequestMapping("/downLoad")
public ModelAndView downLoad(String filePath,HttpServletResponse response) throws Exception {
String p=filePath.substring(filePath.lastIndexOf("\\")+1);
File f=new File(filePath);
if(f.exists()){
FileInputStream input= new FileInputStream(filePath);//读取文件的IO流
BufferedInputStream in=new BufferedInputStream(input);//放到缓冲流里
response.setContentType("application/msword");
ServletOutputStream out=response.getOutputStream();
response.setHeader("Content-disposition","attachment;filename="+ URLEncoder.encode(p, "UTF-8"));//设置头部信息
int bytesRead = 0;
byte[] buffer = new byte[2048];
//开始向网络传输文件流
System.out.println("--"+bytesRead);
while (-1!=(bytesRead = in.read(buffer, 0, buffer.length))) {
out.write(buffer, 0, bytesRead);
}
out.flush();//这里一定要调用flush()方法,到硬盘
out.close();
in.close();
input.close();
}else{
PrintWriter out=response.getWriter();
out.write("不好意思啊,该文件出去玩了,不在家!");
}
return null;
}
- springMVC上传下载
- SpringMVC上传下载.
- SpringMVC上传下载
- springMvc上传下载
- springmvc上传下载
- SpringMVC上传下载
- springmvc上传下载
- SpringMVC上传下载
- SpringMVC 上传下载
- springMVC上传下载
- SpringMVC中文件上传下载
- Springmvc上传下载附件
- springmvc文件上传下载
- springmvc文件上传下载
- SpringMVC 文件上传下载
- springmvc文件上传下载
- SpringMVC 上传下载(1)
- springmvc实现文件上传下载
- Hive到底是什么?
- 字符编码详解及由来(UNICODE,UTF-8,GBK)
- Android-ExifInterface如何正确存取Double类型坐标 .
- MySQL 彻底卸载与安装
- 建议通过从属营销增加利润
- springMVC上传下载
- 扩展ListView的实现重点(ExpandableListView的强调点)
- 英语学习——————20140110
- Spring ReflectionUtils工具类代码
- 45个超实用Javascript技巧
- 几秒前,几分钟前,几小时前,几天前,几月前,几年前的实现
- 11
- erlang递归和尾递归
- 11