Spring MVC 文件上传下载

时间:2025-04-16 17:46:24

相关资源下载地址:/detail/geloin/4506561

        本文基于Spring MVC 注解,让Spring跑起来

        (1) 导入jar包:、、。

        (2) 在src/context/中添加

<bean 
	class=""
	p:defaultEncoding="UTF-8" />


注意,需要在头部添加内容,添加后如下所示:

<beans default-lazy-init="true"
	xmlns="/schema/beans"
	xmlns:p="/schema/p"
	 xmlns:xsi="http:///2001/XMLSchema-instance"
	xmlns:context="/schema/context"
	xmlns:mvc="/schema/mvc"
	xsi:schemaLocation="  
       /schema/beans   
       /schema/beans/spring-beans-3.  
       /schema/mvc   
       /schema/mvc/spring-mvc-3.   
       /schema/context  
       /schema/context/spring-context-3.">

        (3) 添加工具类

/**
 *
 * @author geloin
 * @date 2012-5-5 下午12:05:57
 */
package ;

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

import ;
import ;

import ;
import ;
import ;
import ;
import ;

/**
 * 
 * @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 = (new SimpleDateFormat("yyyyMMddHHmmss")
				.format(new Date()));
		Long random = (long) (() * now);
		String fileName = now + "" + random;

		if ((".") != -1) {
			fileName += (("."));
		}

		return fileName;
	}

	/**
	 * 压缩后的文件名
	 * 
	 * @author geloin
	 * @date 2012-3-29 下午6:21:32
	 * @param name
	 * @return
	 */
	private static String zipName(String name) {
		String prefix = "";
		if ((".") != -1) {
			prefix = (0, ("."));
		} 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 = ();

		String uploadDir = ().getServletContext()
				.getRealPath("/")
				+ ;
		File file = new File(uploadDir);

		if (!()) {
			();
		}

		String fileName = null;
		int i = 0;
		for (Iterator<<String, MultipartFile>> it = ()
				.iterator(); (); i++) {

			<String, MultipartFile> entry = ();
			MultipartFile mFile = ();

			fileName = ();

			String storeName = rename(fileName);

			String noZipName = uploadDir + storeName;
			String zipName = zipName(noZipName);

			// 上传成为压缩文件
			ZipOutputStream outputStream = new ZipOutputStream(
					new BufferedOutputStream(new FileOutputStream(zipName)));
			(new ZipEntry(fileName));
			("GBK");

			((), outputStream);

			Map<String, Object> map = new HashMap<String, Object>();
			// 固定参数值对
			(, zipName(fileName));
			(, zipName(storeName));
			(, new File(zipName).length());
			(, "zip");
			(, "application/octet-stream");
			(, new Date());

			// 自定义参数值对
			for (String param : params) {
				(param, (param)[i]);
			}

			(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 {
		("text/html;charset=UTF-8");
		("UTF-8");
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;

		String ctxPath = ().getServletContext()
				.getRealPath("/")
				+ ;
		String downLoadPath = ctxPath + storeName;

		long fileLength = new File(downLoadPath).length();

		(contentType);
		("Content-disposition", "attachment; filename="
				+ new String(("utf-8"), "ISO8859-1"));
		("Content-Length", (fileLength));

		bis = new BufferedInputStream(new FileInputStream(downLoadPath));
		bos = new BufferedOutputStream(());
		byte[] buff = new byte[2048];
		int bytesRead;
		while (-1 != (bytesRead = (buff, 0, ))) {
			(buff, 0, bytesRead);
		}
		();
		();
	}
}

        可完全使用而不必改变该类,需要注意的是,该类中设定将上传后的文件放置在WebContent/uploadDir下。

        (4) 添加

/**
 *
 * @author geloin
 * @date 2012-5-5 上午11:56:35
 */
package ;

import ;
import ;
import ;

import ;
import ;

import ;
import ;
import ;
import ;

import ;

/**
 * 
 * @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 = (request,
				"alais");

		String[] params = new String[] { "alais" };
		Map<String, Object[]> values = new HashMap<String, Object[]>();
		("alais", alaises);

		List<Map<String, Object>> result = (request,
				params, values);

		("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 = "";
		String realName = "Java设计模式.zip";
		String contentType = "application/octet-stream";

		(request, response, storeName, contentType,
				realName);

		return null;
	}
}


下载方法请自行变更,若使用数据库保存上传文件的信息时,请参考Spring MVC 整合Mybatis实例


        (5) 添加fileOperate/

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="/jsp/jstl/core"%>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http:///TR/xhtml1/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/" />" 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/

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="/jsp/jstl/core"%>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http:///TR/xhtml1/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="${ eq 'realName' }">
				${ }
			</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/下载文件