File upload public class Upservlet extends HttpServlet {Public void Doget (HttpServletRequest request, httpservletresponse response)throws Servletexception, IOException {request.setcharacterencoding ("Utf-8");Response.setcontenttype ("Text/html;charset=utf-8");PrintWriter pout=response.getwriter ();try {//Get the real path to the upload fileString Storepath=getservletcontext (). Getrealpath ("Web-inf/files");//Setting up the environmentdiskfileitemfactory factory=new diskfileitemfactory ();factory.setrepository (New File (Getservletcontext (). Getrealpath ("/temp" ));//Determine if the form is of type Enctype=multipart/form-dataBoolean ismutipart=servletfileupload.ismultipartcontent (request);if (!ismutipart) {System.out.println ("rookie");return; }//Servletfileupload Core classservletfileupload upload=new servletfileupload (factory);//Upload.setprogresslistener (New Progresslistener () {////pbytesread: Current number of bytes to read////pcontentlength: Length of File////pitems: The first few//Public void Update (Long pbytesread, long pcontentlength,//int Pitems) {//System.out.println ("read:" +pbytesread+ ", File Size:" +pcontentlength+ ", Number of items:" +pitems ");// }//// });//Upload.setfilesizemax (4 * 1024 * 1024);//Set the size of a single upload file//Upload.setsizemax (6 * 1024 * 1024);//Set Total file sizeAnalyticallist<fileitem> items=upload.parserequest (request);For (Fileitem item:items) {if (Item.isformfield ()) {String fieldname=item.getfieldname ();String fieldvalue=item.getstring ("Utf-8");System.out.println (fieldName + "=" + Fieldvalue);}else{//Get MIME typeString Mimetype=item.getcontenttype ();//allow uploading of images onlyif (Mimetype.startswith ("image")) {//Upload fieldInputStream In=item.getinputstream ();//uploaded file nameString filename=item.getname ();//If the file is not filled skipif (filename==null&& "". Equals (Filename.trim () )) {continue; }filename=filename.substring (filename.lastindexof ("\ \") +1);Filename=uuid.randomuuid () + "_" +filename;System.out.println (request.getremoteaddr () + "==============" +filename);//Build output stream//Scatter storage directoryString Newstorepath=makestorepath (storepath,filename);////web-inf/files and file name to create a new storage path///WEB-INF/FILES/1/12String storefile=newstorepath+ "\ \" +filename;outputstream out=new FileOutputStream (storefile);//Set Cachebyte b[]=new byte[1024];int len=-1;While ((Len=in.read (b))!=-1) {Out.write (B,0,len); }out.close ();in.close ();item.delete ();//delete temporary files } } }} catch (Fileuploadexception e) {throw new RuntimeException ("Server Busy! "); }request.getrequestdispatcher ("/servlet/showallfilesservlet"). Forward (request, response); }Public void DoPost (HttpServletRequest request, httpservletresponse response)throws Servletexception, IOException {doget (request,response); }private String Makestorepath (String Storepath, String fileName) {Create a new storage path based on/web-inf/files and file name/WEB-INF/FILES/1/12int Hashcode=filename.hashcode ();int dir1=hashcode&0xf;int dir2= (hashcode&0xf0) >>4;String path=storepath+ "\ \" +dir1+ "\ \" +DIR2;file File=new file (path);if (!file.exists ())file.mkdirs ();return path; }}//file download public class Downservlet extends HttpServlet {Public void Doget (HttpServletRequest request, httpservletresponse response)throws Servletexception, IOException {Response.setcontenttype ("Text/html;charset=utf-8");OutputStream Out=response.getoutputstream ();String filename=request.getparameter ("filename");filename=new String (filename.getbytes ("iso-8859-1"), "Utf-8");//Intercept old file namesString Oldfilename=filename.split ("_") [1];//Get storage pathString Storepath=getservletcontext (). Getrealpath ("/web-inf/files");//Get the full path of the fileString Filepath=makestorepath (storepath,filename) + "\ \" +filename;//Determine if the file existsfile File=new file (filePath);if (!file.exists ()) {Out.write ("from the contrast! The file you want to download may no longer exist ". GetBytes (" UTF-8 "));return; }inputstream in=new fileinputstream (file);//Notifies the client to open the way it is downloadedResponse.setheader ("Content-disposition", "Attachment;filename=" +urlencoder.encode (OldFileName, "UTF-8"));byte[] b = new byte[1024];int len =-1;While ((Len=in.read (b))!=-1) {Out.write (b, 0, Len); }in.close ();out.write ("Download succeeded". GetBytes ("UTF-8")); }private String Makestorepath (string storepath, string filename) {int hashcode = Filename.hashcode ();int dir1 = hashcode & 0xf;//0000~1111: integer 0~15 total 16int dir2 = (hashcode & 0xf0) >> 4;//0000~1111: integer 0~15 total 16 String Path = storepath + "\ \" + dir1 + "\ \" + Dir2;//WEB-INF/FILES/1/12File File = new file (path);if (!file.exists ())file.mkdirs ();return path; }Public void DoPost (HttpServletRequest request, httpservletresponse response)throws Servletexception, IOException {doget (request,response); }}//download page <body> <c:url value= "/servlet/downservlet" var= "url" ><c:param name= "filename" value= "${me.key}" ></c:param></c:url>${me.value} <a href= "${url}" > Downloads </a><br/></c:forEach> </body>Public
class Showallfilesservlet extends HttpServlet {
Public void Doget (HttpServletRequest request, httpservletresponse response)
throws Servletexception, IOException {
map<string,string> map=new hashmap<string,string> ();//key:uuid file name; value: Old file name
//Get the root directory of the stored files
String Storepath=getservletcontext (). Getrealpath ("/web-inf/files");
//Recursive traversal of the file
file File=new file (storepath);
Treewalk (file,map);
//Give JSP to show: how to encapsulate data. In map encapsulation. Key:uuid file name; value: Old file name
Request.setattribute ("map", map);
request.getrequestdispatcher ("/down.jsp"). Forward (request, response);
}
private void Treewalk (file file, map<string, string> Map) {
//Traverse/web-inf/files All files and put the file name in map
if (File.isfile ()) {
//is a file
String uuidname=file.getname ();
String oldname=uuidname.substring (Uuidname.indexof ("_") +1);
map.put (Uuidname, oldname);
}else{
//is a directory
file[] Fs=file.listfiles ();
For (File f:fs) {
Treewalk (f,map);
}
}
}
Public void DoPost (HttpServletRequest request, httpservletresponse response)
throws Servletexception, IOException {
doget (request,response);
}
}
File upload Download