Reprint please specify the original address: http://www.cnblogs.com/ygj0930/p/6128382.html
In front (http://www.cnblogs.com/ygj0930/p/6073505.html) We mentioned the implementation of Javaweb developed file upload function, need to use third-party jar package, and to create factory Ah, Set temporary file area path Yes, wait, it's tedious. As a developer, it is not possible to do so many operations every time a file is uploaded. At this point, we can encapsulate these tedious tasks and make a function of the functions to call the method. When we implement the file upload, we simply import the tool class, and then call the appropriate method. Therefore, we have the idea of the File Upload Tool class.
The essence of the File Upload Tool class is to encapsulate the tedious work according to the function block, and the outside world can call the function by the function name to get the result. So, in the process of file upload, we need to use the common functions of what? My tool class here probably implements the following, and there are many more features that the reader can implement on demand:
Set Save path
Set Buffer path
Set Buffer size
Set File type
Get file name extension
Verifying File type Validity
Form Content acquisition: text is saved in a map with key-value pairs. Save the file to the Save directory
Get uploaded file contents (return map to caller)
Here is the source code:
To import the required classes:
ImportJava.util.*;Importjava.lang.*;ImportJava.io.File;ImportJava.util.HashMap;Importjava.util.List;ImportJava.util.Map;Importjavax.servlet.http.HttpServletRequest;ImportOrg.apache.commons.fileupload.FileItem;Importorg.apache.commons.fileupload.disk.DiskFileItemFactory;ImportOrg.apache.commons.fileupload.servlet.ServletFileUpload;
Defines a series of alternate variables, arrays, class objects to be used, a series of constructors for a tool class, etc.
PrivateString[] Filetypes=NULL;//the types of files that are allowed to be uploaded PrivateString dstpath=NULL;//File Save path Private Longfilesizemax=10*1024*1024;//maximum number of files allowed to upload PrivateString cachepath=NULL;//Cache Path Private intcachesizemax=5*1024*1024;//Maximum cache capacity PrivateMap<string,string> textcontent;//upload the text content in the form to save it with a map PrivateServletfileupload Sfupload;//main classes to implement upload functionality PrivateDiskfileitemfactory factory=NewDiskfileitemfactory ();//define the factory to configure the upload path, buffer location, etc. PublicMyuploadutil () {}; PublicMyuploadutil (String dst,string cache,string[] filetypes,LongFilesizemax,intCachesizemax) { Super(); This. dstpath=DST; This. cachepath=Cache; This. filetypes=filetypes; This. filesizemax=Filesizemax; This. cachesizemax=Cachesizemax; } Publicmyuploadutil (String dst,string cache,string[] filetypes) {Super(); This. dstpath=DST; This. cachepath=Cache; This. filetypes=filetypes; }
Define the SETXX () method for external calls to set the path value, cache path, file type, and so on:
Public voidSetcachepath (String cachepath) { This. cachepath=CachePath; } Public voidSetCacheSize (intsize) { This. cachesizemax=size; } Public voidSetdstpath (String path) { This. dstpath=path; } Public voidSetfilesize (Longsize) { This. filesizemax=size; } Public voidSetfiletype (string[] types) { This. filetypes=types; }
Define a range of functional methods: Get content, determine file type legitimacy, and more:
//get file name extension Publicstring getfileext (file file) {string path=File.getname (); returnPath.substring (Path.lastindexof (".") +1); } //for outside calls get the text content in the upload form PublicMap<string,string>gettextcontent () {returntextcontent; } //The extracted text content is assigned to the map object of the class itself for external access Public voidSettextcontent (map<string,string>map) { This. textcontent=map; } //Singleton mode Gets the file upload class, if it does not exist, it is created, and is assigned to Sfuload to avoid duplicate creation Publicservletfileupload getservletfileupload () {if(sfupload==NULL) {Sfupload=Newservletfileupload (Factory); returnSfupload; }Else{ returnSfupload; } } //determine whether a file is a valid type Public Booleanisfilevalidate (file file) {if(filetypes==NULL){return true;} for(inti=0;i<filetypes.length;++i) { if(Filetypes[i].equals (getfileext (file))) {return true; } } return false; } //Create a file directory: Used to create files to save directories, cache directories, and then follow paths Public voidmakedir (String URL) {File file=NewFile (URL); if(!file.exists ()) { if(!File.mkdirs ()) {System.out.println ("Fail to create dir!"); } } }
Finally, define the upload method:
//Upload Method Public voidupload (HttpServletRequest request) {Try{ if(!servletfileupload.ismultipartcontent (Request)) { return; } makedir (Dstpath);//Create file Save directoryMakeDir (CachePath);//Create a cache directoryFactory.setrepository (NewFile (CachePath));//set the cache pathFactory.setsizethreshold (Cachesizemax);//Setting the cache sizeServletfileupload sfu=getservletfileupload ();//Get upload classSfu.setfilesizemax (Filesizemax);//set the maximum allowable value for an upload fileList<FileItem> items=sfu.parserequest (Request);//extract the files that came with the requestmap<string,string> map =NewHashmap<string,string> ();//Create a Map object to extract the text content from the upload form//iterative extraction of uploaded filesIterator it=Items.iterator (); while(It.hasnext ()) {Fileitem Fileitem=(Fileitem) it.next (); if(Fileitem.isformfield ()) {//if it's text content, extract it and put it in the map.Map.put (Fileitem.getfieldname (), fileitem.getstring ("UTF-8")); }Else{//if it is not text, the fileString Path=fileitem.getname ();//Get file name LongSize=fileitem.getsize ();//Get File Size if("". Equals (path) | | Size = = 0) {//Judgment of invalid fileSystem.out.println ("Not validate file"); return; } File File=NewFile (Dstpath,NewFile (Fileitem.getname ()). GetName ());//create a file with the same name under File save path based on filename if(!isfilevalidate (file)) {//determine if the file type is legalSystem.out.println ("File type incorrect!"); }Else{fileitem.write (file);//file is valid, the upload file is written to the file path via IO stream}}} settextcontent (map);//after the form text is extracted, the contents of the map are set to the Textcontent object in the class. }Catch(Exception ex) {System.out.println (ex); } }
Using the tool class:
Below, let's simply try to use our packaged File Upload tool classes in real-world applications:
<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" Utf-8 "%><% @pageImport= "Java.io.*"%><% @pageImport= "javax.servlet.*"%><% @pageImport= "javax.servlet.http.*"%><% @pageImport= "org.apache.commons.fileupload.servlet.*"%><% @pageImport= "Upload.myuploadutil"%><%//define which file types are allowed to be uploaded FinalString allowedext[] ={"JPG", "GIF"}; //gets the absolute path of the Web app on the Web server to save the fileString realwebbase = Request.getsession (). Getservletcontext (). Getrealpath ("/"); //Create temporary file save directory under File save directoryString temp_file = realwebbase+ "Upload\\uploadtemp"; Myuploadutil Myupload=NewMyuploadutil (Realwebbase,temp_file,allowedext);//Create the File Upload Tool class object, initialize the file save path, etc. as a parameterMyupload.upload (Request);//object calls the upload method to implement the upload function%>
File Upload Tool class--fool upload file