First, the introduction of JAR package
1. Commons-fileupload-1.2.1.jar
2. Commons-io-1.4.jar
Second, file upload
1. HTML code
1 <formname= "Upload_test"Action= "${pagecontext.request.contextpath}/fileservlet?method=upload"Method= "POST"enctype= "Multipart/form-data">2User name:<inputtype= "text"name= "UserName" > <BR>3File:<inputtype= "File"name= "FileName" > <BR>4 <inputtype= "Submit"value= "Upload" >5 </form>
2. Java code
1 Private voidUpload (httpservletrequest request, httpservletresponse response)2 throwsservletexception, IOException {3String URI =NULL;4 Try {5 //File Upload Factory6Fileitemfactory factory =Newdiskfileitemfactory ();7 //File Upload core tool class8Servletfileupload upload =Newservletfileupload (factory);9 /*** * * Set Size LIMIT Parameters * * * **/Ten //Single File size limit OneUpload.setfilesizemax (10*1024*1024); A //total File size limit -Upload.setsizemax (50*1024*1024); - //encoding and processing of Chinese files theUpload.setheaderencoding ("UTF-8"); - //Judging: Whether the current form is a file upload form - if(upload.ismultipartcontent (Request)) { - //convert the request data to a Fileitem object, and then encapsulate it in a collection +list<fileitem> list =upload.parserequest (request); - //traverse: Get each uploaded data + for(Fileitem item:list) { A //Judging type (true: Normal form | | false: Upload form) at if(Item.isformfield ()) { - //Get name -String name =item.getfieldname (); - //Get Value -String value =item.getstring (); - //Print Content inSystem.out.println ("Name:" + name + "\tvalue:" +value); -}Else { to /*** * * Upload FORM * * * **/ + //Get file name -String name =item.getname (); the //----deal with the name of uploading file names---- * //gets a 36-bit UUID string $String ID =Uuid.randomuuid (). toString ();Panax Notoginseng //Stitching file name -Name = ID + "#" +name; the //Get upload directory +String basepath = Getservletcontext (). Getrealpath ("Upload"); ASystem.out.println ("BasePath:" +basepath); the //Create a File object to upload +File File =NewFile (basepath, name); - //Upload $ item.write (file); $ //Delete temporary files that are generated when the component runs - Item.delete (); - } the } -}Else {WuyiSystem.out.println ("Not upload form"); the } - WuURI = "/success.jsp"; -}Catch(fileuploadexception e) { About e.printstacktrace (); $URI = "/error/error.jsp"; -}Catch(Exception e) { - e.printstacktrace (); -URI = "/error/error.jsp"; A}finally { + Request.getrequestdispatcher (URI). Forward (request, response); the } -}
Third, File download
------------------digging pits to fill----------
Javaweb file upload Download, use FileUpload component