java中的接口是类吗
200
2023-06-19
Spring MVC 文件上传下载的实例
Spring MVC 文件上传下载,具体如下:
(1) 导入jar包:ant.jar、commons-fileupload.jar、connom-io.jar。
(2) 在src/context/dispatcher.xml中添加
class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="UTF-8" /> 注意,需要在头部添加内容,添加后如下所示: xmlns="http://springframework.org/schema/beans" xmlns:p="http://springframework.org/schema/p" xmlns:xsi="http://w3.org/2001/XMLSchema-instance" xmlns:context="http://springframework.org/schema/context" xmlns:mvc="http://springframework.org/schema/mvc" xsi:schemaLocation=" http://springframework.org/schema/beans http://springframework.org/schema/beans/spring-beans-3.0.xsd http://springframework.org/schema/mvc http://springframework.org/schema/mvc/spring-mvc-3.0.xsd http://springframework.org/schema/context http://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 gqyuEccIBerandom = (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 gqyuEccIBe String[] params, Map List MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request; Map 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 .iterator(); it.hasNext(); i++) { Map.Entry 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 // 固定参数值对 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[] alaises = ServletRequestUtils.getStringParameters(request, "alais"); String[] params = new String[] { "alais" }; Map values.put("alais", alaises); List 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"%>
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:defaultEncoding="UTF-8" />
注意,需要在头部添加内容,添加后如下所示:
xmlns="http://springframework.org/schema/beans" xmlns:p="http://springframework.org/schema/p" xmlns:xsi="http://w3.org/2001/XMLSchema-instance" xmlns:context="http://springframework.org/schema/context" xmlns:mvc="http://springframework.org/schema/mvc" xsi:schemaLocation=" http://springframework.org/schema/beans http://springframework.org/schema/beans/spring-beans-3.0.xsd http://springframework.org/schema/mvc http://springframework.org/schema/mvc/spring-mvc-3.0.xsd http://springframework.org/schema/context http://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 gqyuEccIBerandom = (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 gqyuEccIBe String[] params, Map List MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request; Map 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 .iterator(); it.hasNext(); i++) { Map.Entry 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 // 固定参数值对 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[] alaises = ServletRequestUtils.getStringParameters(request, "alais"); String[] params = new String[] { "alais" }; Map values.put("alais", alaises); List 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"%>
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
xmlns="http://springframework.org/schema/beans"
xmlns:p="http://springframework.org/schema/p"
xmlns:xsi="http://w3.org/2001/XMLSchema-instance"
xmlns:context="http://springframework.org/schema/context"
xmlns:mvc="http://springframework.org/schema/mvc"
xsi:schemaLocation="
http://springframework.org/schema/beans
http://springframework.org/schema/beans/spring-beans-3.0.xsd
http://springframework.org/schema/mvc
http://springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://springframework.org/schema/context
http://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 gqyuEccIBerandom = (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
gqyuEccIBe String[] params, Map
List
MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
Map
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
.iterator(); it.hasNext(); i++) {
Map.Entry
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
// 固定参数值对
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[] alaises = ServletRequestUtils.getStringParameters(request,
"alais");
String[] params = new String[] { "alais" };
Map
values.put("alais", alaises);
List
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"%>
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
http://
action="
确保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"%>
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
${m.value }
(7) 通过http://localhost:8080/spring_test/background/fileOperate/to_upload.html访问上传页面,通过http://localhost:8080/spring_test/background/fileOperate/download.html下载文件
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~