<input type= "File" id= "file" name= "file" >
The configuration in spring:
<!--upload Attachments--
<bean id= "Multipartresolver" class= "Org.springframework.web.multipart.commons.CommonsMultipartResolver" >
<property name= "defaultencoding" value= "Utf-8"/>
<!--upload maximum limit 20m-->
<property name= "maxuploadsize" value= "20971520"/>
<property name= "maxinmemorysize" value= "40960"/>
<!--resolvelazily property is enabled to defer file parsing so that the file size is caught in the uploadaction exception-
<property name= "resolvelazily" value= "true"/>
</bean>
Use Ant's ZipFile object because it can set encoding problem to solve Chinese garbled characters:
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.7.0</version>
</dependency>
@RequestMapping (value = "/add")
Public String Add (@RequestParam ("file") commonsmultipartfile file, mktspecial mktspecial,httpsession session, HttpServletRequest request, HttpServletResponse response) throws exception{
Clear last Upload progress information
String Curprojectpath = Session.getservletcontext (). Getrealpath ("/");
String Savedirectorypath = Curprojectpath + uploadfoldername;
Log.info ("Upload Save directory:" +savedirectorypath);
String Unzippath = Curprojectpath + Mktspecial.gethtmlen ();
Log.info ("Upload unzip theme directory:" +unzippath);
File Savedirectory = new file (Savedirectorypath);
if (!savedirectory.isdirectory ()) {
Savedirectory.mkdir ();
}
File Unzippathdirectory = new file (Unzippath);
if (!unzippathdirectory.isdirectory ()) {
Unzippathdirectory.mkdir ();
}
Log.info ("Project Real path [" + Savedirectory.getabsolutepath () + "]");
Determine if a file exists
if (!file.isempty ()) {
String fileName = File.getoriginalfilename ();
Mktspecial.setzipname (FileName);
String fileextension = filenameutils.getextension (fileName);
if (! Arrayutils.contains (Extensionpermit, fileextension)) {
Log.info ("The compressed file extension of the topic list is not correct");
throw new Exception ("No support extension.");
}
Write the file directly by Commonsmultipartfile (note this time)
File Newuploadfile=new file (savedirectory, fileName);
File.transferto (Newuploadfile);
Unzip
Ziptofile (Savedirectorypath+file.separator +filename, Unzippath);
Delete the original upload file
Newuploadfile.delete ();
}
Mktspecial.setcreatetime (New Date ());
Mktspecial.setisusable (Constants.UsableStatus.YES);
int addcount=mktspecialservice.insertselective (mktspecial);
if (addcount>0) {
Setusermanageoperatelog (Request,constants.usermanageoperatemode.other,constants.usermanageoperatetype.add, " Increased thematic success ", Jsonobject.tojsonstring (mktspecial));
}else{
Setusermanageoperatelog (Request,constants.usermanageoperatemode.other,constants.usermanageoperatetype.add, " Increased thematic failure ", jsonobject.tojsonstring (mktspecial));
}
Return Redirectto ("/mktspecial/list");
}
/**
* Unzip zip file
* @param sourcefile, zip file to unzip; Tofolder, the storage path after decompression
* @throws Exception
**/
public static void Ziptofile (String sourcefile, String tofolder) throws Exception {
String Todisk = tofolder;//receives the extracted storage path
ZipFile zfile = new ZipFile (sourcefile, "utf-8");//Connect the files to be unzipped
Enumeration zlist = Zfile.getentries ();//Get all the elements in the ZIP package
ZipEntry ze = null;
byte[] buf = new byte[1024];
while (Zlist.hasmoreelements ()) {
Ze = (zipentry) zlist.nextelement ();
if (Ze.isdirectory ()) {
Log.info ("Open the folder in the zip file:" + ze.getname () + "skipped ...");
Continue
}
OutputStream Outputstream=null;
InputStream InputStream =null;
try {
Take zipentry as parameter to get a inputstream, and write to OutputStream
OutputStream = new Bufferedoutputstream (
New FileOutputStream (Getrealfilename (Todisk, Ze.getname ()));
InputStream = new Bufferedinputstream (Zfile.getinputstream (Ze));
int readlen = 0;
while ((Readlen = Inputstream.read (buf, 0, 1024))! =-1) {
Outputstream.write (buf, 0, Readlen);
}
Inputstream.close ();
Outputstream.close ();
} catch (Exception e) {
Log.info ("Decompression failed:" +e.tostring ());
throw new IOException ("Decompression failed:" + e.tostring ());
}finally{
if (InputStream! = null) {
try {
Inputstream.close ();
} catch (IOException ex) {
}
}
if (outputstream! = null) {
try {
Outputstream.close ();
} catch (IOException ex) {
Ex.printstacktrace ();
}
}
Inputstream=null;
Outputstream=null;
}
}
Zfile.close ();
}
/**
* Given the root directory, returns the actual file name corresponding to a relative path.
* @param zippath Specify root directory
* @param absfilename relative path name, from name in ZipEntry
* @return Java.io.File actual file
*/
private static File Getrealfilename (String zippath, String absfilename) {
Log.info ("FileName:" +absfilename);
string[] dirs = Absfilename.split ("/", Absfilename.length ());
Files ret = new file (zippath);//Create File Object
if (Dirs.length > 1) {
for (int i = 0; i < dirs.length-1; i++) {
ret = new File (ret, dirs[i]);
}
}
if (!ret.exists ()) {//detects if file exists
Ret.mkdirs ();//Create the directory specified by this abstract path name
}
ret = new file (ret, dirs[dirs.length-1]);//Create a new file instance based on the RET abstract path name and the child pathname string
return ret;
}
Springmvc uploading a ZIP file and extracting the code sample