Related Resources Download Address: http://download.csdn.net/detail/geloin/4506561
This article is based on spring MVC annotations and lets spring run.
(1) Import jar package: Ant.jar, Commons-fileupload.jar, Connom-io.jar.
(2) Add in Src/context/dispatcher.xml
<bean id= "Multipartresolver"
class= "Org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:defaultencoding= "UTF-8"/>
Note that you need to add content to the header, as follows:
<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) Add tool class Fileoperateutil.java
/** * * @author geloin * @date 2012-5-5 PM 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 PM 12:05:57 */public class Fileoperateutil {private static final String REA
LNAME = "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 pm 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; /** * Compressed file name * * @author geloin * @date 2012-3-29 pm 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"; /** * Upload file * * @author geloin * @date 2012-5-5 PM 12:25:47 * @param request * @param params * @param val UES * @return * @throws Exception * * public static list<map<string, object>> upload (httpservletrequest Request, string[] params, map<string, object[]> values) throws Exception {list<map<string, OBJECT>&G T
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); Upload as a compressed file Zipoutputstream OutputStream = new Zipoutputstream (New Bufferedoutputstream (FileOutputStream
AME));
Outputstream.putnextentry (New ZipEntry (FileName));
Outputstream.setencoding ("GBK");
Filecopyutils.copy (Mfile.getinputstream (), outputstream);
map<string, object> map = new hashmap<string, object> ();
Fixed parameter values to 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 ()); Custom parameter value pair for (String param:params) {Map.put(Param, Values.get (param) [i]);
} result.add (map);
} return result; */** * Download * * @author geloin * @date 2012-5-5 PM 12:25:39 * @param request * @param response * @param sto ReName * @param contentType * @param realname * @throws Exception */public static void Download (Httpservletreque
St 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 ();
}
}
Can be fully used without changing the class, it is important to note that the class is set to place the uploaded file under Webcontent/uploaddir.
(4) Add Fileoperatecontroller.java
/** * * @author geloin * @date 2012-5-5 Morning 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 Morning 11:56:35 */@Controller @RequestMapping (value = "background/fileoperate") p
Ublic class Fileoperatecontroller {/** * to the location of the uploaded file * * @author geloin * @date 2012-3-29 pm 4:01:31 * @return */@RequestMapping (value = "to_upload") public Modelandview Toupload () {return new Modelandview ("Background/fileopera
Te/upload "); }/** * Upload file * * @author geloin * @date 2012-3-29 pm 4:01:41 * @param reqUest * @return * @throws Exception */@RequestMapping (value = "Upload") public Modelandview upload (httpservletrequ
EST request) throws Exception {map<string, object> Map = new hashmap<string, object> ();
Alias 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); */** * Download * * @author geloin * @date 2012-3-29 PM 5:24:14 * @param attachment * @param request * @param r Esponse * @return * @throws Exception */@RequestMapping (value = "Download") Public Modelandview Download (httpserv Letrequest request, HttpServletResponse response) throws Exception {StringStoreName = "201205051340364510870879724.zip";
String realname = "Java design mode. zip";
String ContentType = "Application/octet-stream";
Fileoperateutil.download (Request, Response, StoreName, ContentType, realname);
return null;
}
}
Please change the download method, if you use the database to save the uploaded file information, please refer to the Spring MVC integration MyBatis instance.
(5) Add 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 ">
Make sure that the value of Enctype is Multipart/form-data;method for post.
(6) Add 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 ">