I. How FILEUPLOAD components work
First, a picture to help you understand
FileUpload Core API
1. Diskfileitemfactory
Constructors
1) diskfileitemfactory ()//Use default configuration
2) diskfileitemfactory (int sizethreshold, File repository)
Sizethreshold memory buffer, cannot be set too large, otherwise it will cause the JVM to crash
Repository Temp file directory
2. Servletfileupload
1) ismutipartcontent (Request)//Determine if the upload form is multipart/form-data type True/false
2) parserequest (Request)//parse request, return value is list<fileitem> type
3) Setfilesizemax (long)//upload file single maximum value
4) Setsizemax (long)//upload the total number of files maximum
5) setheaderencoding (String)//Set encoding format
6) Setprogresslistener (Progresslistener)//Setup listener, can be used to make progress bar
Two. Use FileUpload to implement file upload 1. Writing JSPs
1 <%@ Page ContentType="Text/html;charset=utf-8"language="Java" %>2 <HTML>3 <Head>4 <title>Presentation File Upload</title>5 </Head>6 <Body>7 <formAction= "${pagecontext.request.contextpath}/servlet/fileupload1"Method= "POST"enctype= "Multipart/form-data">8User name:<inputtype= "text"name= "username"/><BR/>9File 1:<inputtype= "File"name= "File1"/><BR/>TenFile 2:<inputtype= "File"name= "File2"/><BR/> One <inputtype= "Submit"/> A </form> - </Body> - </HTML>
Points:
1) When the form contains a file type entry, the Enctype property must be set to Multipart/form-data
2) Input:file must specify the Name property
3) Form submission is post because a GET request cannot carry large amounts of data
4) If the form is submitted in Multipart/form-data, then the servlet cannot use the GetParameter method to get the form data, and can get all the uploaded data and parse it by getting the input stream of the client submission data.
1 // gets the input stream of the client submission data 2 request.getinputstream ();
5) Difficult to parse data, generally do not write their own programs, you can use open source projects to parse data
2. Writing a servlet
1 Public classFileUpload1extendsHttpServlet {2 @Override3 protected voidDoget (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {4 5InputStream in =NULL;6OutputStream out =NULL;7 8 Try {9 //To create a parser factory using the default configurationTenDiskfileitemfactory factory =Newdiskfileitemfactory (); One //Get parser AServletfileupload upload =Newservletfileupload (factory); - //whether the upload form is a multipart/form-data type - if(!upload.ismultipartcontent (Request)) { the return; - } - //parsing the input stream of the request -List<fileitem> fileitemlist =upload.parserequest (request); + //iterating the list collection - for(Fileitem fileitem:fileitemlist) { + if(Fileitem.isformfield ()) { A //normal field atString name =fileitem.getfieldname (); -String value =fileitem.getstring (); -SYSTEM.OUT.PRINTLN (name + "=" +value); -}Else { - //Uploading Files - //Get upload file name inString FileName =fileitem.getname (); -FileName = filename.substring (filename.lastindexof ("\ \") +1); to //Get input stream +in =Fileitem.getinputstream (); - the //get the upload file directory *String Savepath = This. Getservletcontext (). Getrealpath ("/web-inf/upload"); $ //if the upload file name does not exist, first create thePanax NotoginsengFile Savepathdir =NewFile (savepath); - if(!savepathdir.exists ()) { the Savepathdir.mkdir (); + } A the //Get output stream +out =NewFileOutputStream (Savepath + "\ \" +fileName); - intLen = 0; $ byte[] buffer =New byte[1024]; $ while((len=in.read (buffer)) > 0) { -Out.write (buffer, 0, Len); - } the } - }Wuyi}Catch(Exception e) { the e.printstacktrace (); -}finally { Wu if(In! =NULL) { - in.close (); About } $ if(Out! =NULL) { - out.close (); - } - } A + } the - @Override $ protected voidDoPost (httpservletrequest req, HttpServletResponse resp)throwsservletexception, IOException { the doget (req, resp); the } the}
1) When creating the upload folder in Web-inf. Idea does not create the upload folder in the Web-inf of the Out directory, it needs to be created manually, so first check if the Upload folder exists
2) When you close the stream in Finally, you should first check if the stream is null, or if the upload form is not of type multipart/form-data, and then executes the finally after the return, the program will show the NPE
3) Remember to configure the servlet mapping path in Web. xml
3. Testing
4. Use the browser to grab the bag
Three. Prohibit others from accessing the upload file directory
The upload file directory should be placed in the Web-inf directory, prohibit others to access the upload file directory, or the hacker may upload a script, and then access the script, the site launched an attack
Example:
1. Hackers upload a JSP file
test.jsp
1 <%2 runtime.getruntime (). EXEC ("shutdown-s-T") // execute Windows command 3 %>
2. Close the server by accessing the file
http://localhost:8080/upload/test.jsp
Note:
1) Runtime class//Call Windows program
2) Window command:
Shutdown-a
Format c \
Four. Issues to be resolved
1. Chinese file name garbled problem
2. Upload file directory, file storage number, using hash algorithm to beat
3. File overwrite problem using UUID as file name
Implementing file uploads with FileUpload (1)