web123456

Spring MVC file upload and download

Related resource download address:/detail/geloin/4506561

This article is based onSpring MVC annotations to make Spring run

(1) Import jar package:,.

(2) Add in src/context/

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


Note that you need to add content to the head, as shown below after adding:

<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) Add tool class

/**
  *
  * @author geloin
  * @date 2012-5-5 12:05:57 pm
  */
 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 pm
  */
 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/";

	 /**
	  * Rename the uploaded file
	  *
	  * @author geloin
	  * @date 2012-3-29 3:39:53 pm
	  * @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;
	 }

	 /**
	  * Compressed file name
	  *
	  * @author geloin
	  * @date 2012-3-29 6:21:32 pm
	  * @param name
	  * @return
	  */
	 private static String zipName(String name) {
		 String prefix = "";
		 if ((".") != -1) {
			 prefix = (0, ("."));
		 } else {
			 prefix = name;
		 }
		 return prefix + ".zip";
	 }

	 /**
	  * Upload file
	  *
	  * @author geloin
	  * @date 2012-5-5 12:25:47 pm
	  * @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);

			 // Upload to a compressed file
			 ZipOutputStream outputStream = new ZipOutputStream(
					 new BufferedOutputStream(new FileOutputStream(zipName)));
			 (new ZipEntry(fileName));
			 ("GBK");

			 ((), outputStream);

			 Map<String, Object> map = new HashMap<String, Object>();
			 // Fixed parameter value pair
			 (, zipName(fileName));
			 (, zipName(storeName));
			 (, new File(zipName).length());
			 (, "zip");
			 (, "application/octet-stream");
			 (, new Date());

			 // Custom parameter value pairs
			 for (String param : params) {
				 (param, (param)[i]);
			 }

			 (map);
		 }
		 return result;
	 }

	 /**
	  * download
	  *
	  * @author geloin
	  * @date 2012-5-5 12:25:39 pm
	  * @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);
		 }
		 ();
		 ();
	 }
 }

It can be used completely without changing the class. It should be noted that the uploaded file is set to place the uploaded file under WebContent/uploadDir.

(4) Add

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

 import ;
 import ;
 import ;

 import ;
 import ;

 import ;
 import ;
 import ;
 import ;

 import ;

 /**
  *
  * @author geloin
  * @date 2012-5-5 11:56:35 AM
  */
 @Controller
 @RequestMapping(value = "background/fileOperate")
 public class FileOperateController {
	 /**
	  * to the location where the file is uploaded
	  *
	  * @author geloin
	  * @date 2012-3-29 4:01:31 pm
	  * @return
	  */
	 @RequestMapping(value = "to_upload")
	 public ModelAndView toUpload() {
		 return new ModelAndView("background/fileOperate/upload");
	 }

	 /**
	  * Upload file
	  *
	  * @author geloin
	  * @date 2012-3-29 4:01:41 pm
	  * @param request
	  * @return
	  * @throws Exception
	  */
	 @RequestMapping(value = "upload")
	 public ModelAndView upload(HttpServletRequest request) throws Exception {

		 Map<String, Object> map = new HashMap<String, Object>();

		 // Alias
		 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);
	 }

	 /**
	  * download
	  *
	  * @author geloin
	  * @date 2012-3-29 5:24:14 pm
	  * @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 design pattern.zip";
		 String contentType = "application/octet-stream";

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

		 return null;
	 }
 }


Please change the download method yourself. If you use the database to save the uploaded file information, please refer toSpring MVC integrates Mybatis instances


(5) Add 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="upload" />
 </form>
 </html>

Make sure the value of enctype is multipart/form-data; the value of method is post.

(6) Add 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) Access the upload page through http://localhost:8080/spring_test/background/fileOperate/to_upload.html, and download the file through http://localhost:8080/spring_test/background/fileOperate/