First, with the STRUTS2 framework
1. Environment construction
1.1 Guide Pack: Conmmons-fileupload-1.2.1.jar Conmmons-io-1.4.jar and other framework jar packages
2. Page: Slightly
3. File Upload:
3.1 Designing a File Upload Tool class: Fileuploadutils
1 Public classfileuploadutils{2 3 //the path to which the file is to be uploaded, configurable4 @Resource5 PrivateString FilePath;6 7 Privatestring Createnewfilepath (String fileName) {8 9 //the original path is the configured filepathTenString basepath=FilePath; One //sub-path is formatted/year/month/day form ASimpleDateFormat sdf=NewSimpleDateFormat ("/yyyy/mm/dd"); -String Subpath=sdf.format (NewDate ()); - the //If no directory folder is created -File dir=NewFile (basepath+subpath); - if(!dir.exists ()) { - //to create a directory folder recursively + dir.mkdirs (); - } + A //new file name is uuid+ file extension atString Newfilename=uuid.randomuuid (). ToString ()// -+filename.substring (Filename.lastindexof (".")); - //This is the newly generated file path -String newfilepath=basepath+subpath+NewFileName; - - returnNewfilepath; in } - to PublicString saveuploadfile (File uploadfile,string fileName) { + //New file path -String newfilepath=Createnewfilepath (filepath,filename); the Try{ * //get file input/output stream $InputStream in=NewFileInputStream (uploadfile);Panax NotoginsengOutputStream out=NewFileOutputStream (newfilepath); - the //write throttling to the destination path file + byte[] buff=New byte[1024]; A intLen=0; the while(Len=in.read (Buff))!=-1){ +Out.write (buff,0, Len); - } $ $ -}Catch(Exception e) { - the Throw Newruntimeexception (); -}finally{Wuyi Try{ the in.close (); -}Catch(Exception e) { Wu Throw Newruntimeexception (); -}finally{ About Try{ $ out.close (); -}Catch(Exception e) { - Throw Newruntimeexception (); - } A + } the - } $ the returnNewfilepath; the } the } the
4. File Download: Struts2 in the package is very simple
1 Public classXxxactionextendsActionsupportImplementsmodeldriven{2 3 //input stream to be used for smashing4 PrivateInputStream InputStream;5 //need to write setter,getter;6 7 //model-driven, simplified reference, replaces Strtus1 's Actionform8 PrivateXXX model=NewXXX ();9 PublicXXX Getmodel () {Ten Returm model; One } A - PublicString Download () { -XXX xxx=Xxxservice.getbyid (Model.getid ()); theinputstream=NewFileInputStream (NewFile (Xxx.getpath ())); - - //solve Chinese garbled problem -String Filename=urlencoder.encode (Xxx.getfilename (), "Utf-8"); +ActionContext.getContext.put ("FileName", fileName); - } +}
The rest is Struts.xml's configuration.
Ii. using pure servlet (cont.)
File upload and download in Java Web development