ImportCom.mysql.jdbc.Buffer;ImportOrg.apache.commons.fileupload.FileItem;ImportOrg.apache.commons.fileupload.ProgressListener;ImportOrg.apache.commons.fileupload.disk.DiskFileItemFactory;ImportOrg.apache.commons.fileupload.servlet.ServletFileUpload;ImportJavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;Importjava.io.*;ImportJava.net.URLEncoder;ImportJava.util.HashMap;ImportJava.util.List;ImportJava.util.Map;ImportJava.util.UUID; /** * Create by Jlimingyang * email:wdful165177@gmail.com * DATE:2017/5/10 * <p> * Upload Tool class * requires commons-io-2.5. JAR * Commons-fileupload-1.3.2.jar * * *Public classuploadanddownload {/** *@paramfilenameOriginal name of the file *@returnUuid+ "_" + original name of file *@Method:Makefilename *@Description:Generates the file name of the uploaded file, with the file name: uuid+ "_" + original name of the file *@Anthor: Wdful */private staticString Makefilename (string filename) {//2.jpg//To prevent file overwrite, to generate a unique file name for the uploaded file returnUuid.randomuuid (). toString () +"_" + filename; /** * To prevent the occurrence of too many files under a directory, use the hash algorithm to break up the storage * *@paramfilenameFileName, to generate a storage directory based on the filename *@paramSavepathFile Storage Path *@returnNew Storage Directory *@Method:Makepath *@Description: *@Anthor: Wdful */private staticString Makepath (string filename, string savepath) {//Get the hashcode value of the filename, and get the filename the address of this string object in memoryintHashcode = Filename.hashcode ();intDir1 = hashcode & 0xf; 0--15intDir2 = (Hashcode & 0xf0) >> 4; 0-15//Construct a new save directory String dir = Savepath +"//" + Dir1 +"//" + Dir2; Upload\2\3 upload\3\5//file can represent either a file or a directory file File =NewFile (dir); If the directory does not existif(!file.exists ())
{//Create directory File.mkdirs (); } returnDir /** * Create by wdful * author:wdful * email:wdful165177@gmail.com * Find directory by file name * * PublicString Findfilesavepathbyfilename (string filename, string saverootpath) {intHashcode = Filename.hashcode ();intDir1 = hashcode & 0xf; 0--15intDir2 = (Hashcode & 0xf0) >> 4; 0-15 String dir = Saverootpath +"//" + Dir1 +"//" + Dir2; Upload\2\3 upload\3\5 File File =NewFile (dir); returnDir }//Upload PublicMap<string, object> uploadfile (String Savepath, String Tempath, String ext_name, HttpServletRequest request) { Ext_name: File name extension Limit//String Ext_name = "gif,jpg,jpeg,png,bmp,swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,
RM,RMVB,DOC,DOCX,XLS,XLSX,PPT,HTM,HTML,TXT,ZIP,RAR,GZ,BZ2 "; String Savepath = this..
Getrealpath ("/web-inf/upload"); String Tempath = This.getservletcontext (). Getrealpath ("/web-inf/temp");intSetsizethreshold = 1024 * 10; Set buffer size defaults to 10KBintSetfilesizemax = 1024 * 1024 * 10;//set maximum upload size for individual filesintSetsizemax = 1024 * 1024 * 1024;//set maximum upload size for all files hashmap<string, object> map =NewHashmap<> (); Map.put ("Status",false); Upload Status Map.put ("MSG","Upload failed. "); Upload return info//definition allow uploaded file extension//upload path to Web-inf can be guaranteed without access to file File =NewFile (Savepath); Determine if there is a saved directory for the uploaded fileif(!file.exists () &&!file.isdirectory ())
{File.mkdir (); }//Generate temp directory File tempfile =NewFile (Tempath);if(!tempfile.exists () &&!tempfile.isdirectory ())
{Tempfile.mkdir (); }//message hint//String msg = "";Try{///Use Apache File Upload component to process file uploads//Create a diskfileitemfactory factory diskfileitemfactory factory =NewDiskfileitemfactory ();
Sets the size of the factory's buffer, and when the uploaded file size exceeds the buffer size, a temporary file is generated to be stored in the specified temporary directory.
Factory.setsizethreshold (Setsizethreshold)//Set buffer size of 100KB, if unspecified, then the buffer size defaults to 10KB//Set the Save directory for temporary files generated when uploading
Factory.setrepository (Tempfile); Create a file upload parser servletfileupload upload =NewServletfileupload (Factory); Monitor File Upload Progress Upload.setprogresslistener (NewProgresslistener () {@OverridePublic voidUpdateLongLLongL1,inti) {System. out. println ("File size is:"+ L1 +", currently processed:"+ L);
/** * File size is: 22480, currently processed: 4096 *}}; Solve the Chinese garbled upload.setheaderencoding of uploading filename ("UTF-8"); To determine if the data submitted is an upload formif(!upload.ismultipartcontent (Request)) { returnMap
//Set the maximum size of a single file to upload, is currently set to 1024*1024 Byte, that is, 1MB Upload.setfilesizemax (Setfilesizemax);
Set the maximum number of uploaded files, maximum = The maximum size of multiple files uploaded at the same time, currently set to 1g Upload.setsizemax (Setsizemax); Using the Servletfileupload parser to parse the upload data, the result returned is a list<fileitem> set, each fileitem corresponding to a form entry list<fileitem> List = Upload.parserequest (request); for(Fileitem item:list) {//Get normal input and file dataif(Item.isformfield ())
{String name = Item.getfieldname (); String value = item.getstring ("Utf-8");
Value = new String (value.getbytes ("iso8859-1"), "UTF-8"); System. out. println (name +":" + value); }Else{String fileName = Item.getname ();if(FileName = =NULL|| Filename.trim (). Equals (" ")) {Continue;
//Note: Different browsers submit the file name is not the same, some browsers submit the filename is a path, such as: C:\a\b\1.txt, and some just simple file name, such as: 1.txt Process the path portion of the file name of the uploaded file that was fetched, leaving only the filename part filename = filename.substring (Filename.lastindexof ("\\") + 1); String fileextname = filename.substring (Filename.lastindexof (".") + 1). toLowerCase (); System. out. println ("Fileextname:"+ Fileextname); Determine the file format that supports uploadingif(! Ext_name.contains (Fileextname)) {Map.put ("MSG","The file format is not correct. Not supported: "+ Fileextname);Continue; //Get file input stream Bufferedinputstream bin =NewBufferedinputstream (Item.getinputstream ()); Savepath = This. Makepath (FileName, Savepath); FileName = This. Makefilename (FileName); System. out. println (Savepath +"----" + FileName); File output stream Bufferedoutputstream bout =NewBufferedoutputstream (NewFileOutputStream (Savepath +"//" + fileName)); Bufferbyte[] buffer =New byte[1024 * 1024 * 2];intlen = 0; while(len = bin.read (buffer))!=-1)
{bout.write (buffer, 0, Len);
} bout.close ();
Bin.close ();
Deletes the temporary files generated when processing file uploads item.delete (); Map.put ("MSG","File upload succeeded." "); returnMap }
}
}Catch(Exception e)
{E.printstacktrace (); } returnMap }//Download PublicMap<string, object> downloadFile (String fileName, String filesaverootpath, httpservletresponse response) {H ashmap<string, object> map =NewHashmap<> (); Map.put ("Status",false); Map.put ("MSG","Download failed!");Try{FileName =NewString (Filename.getbytes ("Iso8859-1"),"UTF-8"); Find directory String path by filename This. Findfilesavepathbyfilename (FileName, Filesaverootpath); Get files to download file File =NewFile (path +"\\" + FileName);if(!file.exists ()) {Map.put ("MSG","file does not exist!"); returnMap ///process filename String realname = filename.substring (Filename.indexof ("_") + 1); Set Response header Response.setheader ("Content-disposition","Attachment;filename="+ Urlencoder.encode (realname,"UTF-8")); Read the file to download Bufferedinputstream bin =NewBufferedinputstream (NewFileInputStream (path +"\\" + fileName)); Output stream Bufferedoutputstream bout =NewBufferedoutputstream (Response.getoutputstream ());byte[] buffer =New byte[1024 * 1024 * 2];intlen=0; while((len=bin.read (buffer))!=-1)
{Bout.write (Buffer,0,len);
} bout.close ();
Bin.close (); Map.put ("Status",true); Map.put ("MSG","The download was successful. "); }Catch(Exception e)
{E.printstacktrace (); } returnMap }
/**
*@paramfileRepresents a file, and also represents a file directory *@paramMapMap collection for storing file names *@Method:ListFile *@Description:Recursively iterate through all the files in the specified directory *@Anthor: Wdful */Public voidListFile (file file, map<string, string> Map) {//If file represents not a file, but a directoryif(!file.isfile ())
{//list all files and directories under this directory file files[] = File.listfiles (); Traversal files[] Array for(File f:files)
{//Recursive listfile (f, map); }
}Else{/** * processing filename, uploaded file is renamed as uuid_ filename, remove uuid_ part of filename file.getname (). IndexOf ("_") retrieve Word The first occurrence of the "_" character in a string, if the file name is similar to: 9349249849-88343-8344_ _ van _ File.getname (). substring (File.getname (). IndexOf (" _ ") +1 after processing you can get an _ _ van _ da. avi Part/String realname = File.getname (). substring (File.getname (). IndexOf ("_") + 1);
File.getname () Gets the original name of the file, which is unique, so it can be used as a key,realname after the name is processed, and may be repeated map.put (File.getname (), realname); }
}
}