File Upload Overview
To achieve web development in the file upload function, you need to complete the following two steps:
Add an upload entry to a Web page
Second, read the uploaded file data in the servlet and save it to the local hard drive.
How do I add an upload entry to a Web page?
<input type= the "file" > tag is used to add a file transfer entry on a Web page, and you should note when transferring entries on a file:
1, you must set the input entry of the Name property, otherwise the browser will not send data uploaded files.
2. The enctype of the form must be set to multipart/ Form-data. After setting this value, when the browser uploads the file, it will attach the file data to the HTTP request message body and use the MIME protocol to describe the uploaded file so as to facilitate the receiver to parse and process the uploaded data.
How do I read the file upload data in the servlet and save it to the local hard drive?
The Request object provides a getInputStream method that can be used to read data submitted by the client. However, because users may upload multiple files at the same time, directly read the upload data in the servlet side, and parse out the corresponding file data separately is a very troublesome work, example.
To facilitate user handling of file upload data, the Apache Open source organization provides an open source component (Commons-fileupload) for handling form file uploads, which has excellent performance and its API is extremely simple, allowing developers to easily implement Web file uploads. Therefore, the implementation of file uploading in web development is usually implemented using the Commons-fileupload component.
Using the Commons-fileupload component to implement file uploads, you need to import the appropriate support jar packages for the component: Commons-fileupload and Commons-io. Commons-io does not belong to the development jar file for the file upload component, but the Commons-fileupload component starts with version 1.1 and requires Commons-io package support when it works.
FileUpload Component Workflow
Core Api-diskfileitemfactory
Diskfileitemfactory is a factory that creates Fileitem objects, a common method of this factory class:
public void Setsizethreshold (int sizethreshold): Sets the size of the memory buffer, with a default value of 10K. When the upload file is larger than the buffer size, the FileUpload component uses the temporary file cache to upload the file.
public void Setrepository (Java.io.File repository): Specifies the temporary file directory, and the default value is System.getproperty ("Java.io.tmpdir").
Public diskfileitemfactory (int sizethreshold, Java.io.File repository): constructor
Core Api-servletfileupload
Servletfileupload is responsible for processing uploaded file data and encapsulating each entry in the form into a Fileitem object. Common methods are:
Boolean ismultipartcontent (HttpServletRequest request): Determine if the uploaded form is a multipart/form-data type
List parserequest (HttpServletRequest request): Parses the Request object, wraps each entry in the form into a Fileitem object, and returns a list collection that holds all fileitem.
Setfilesizemax (Long Filesizemax): Sets the maximum value of the uploaded file
Setsizemax (Long Sizemax): Sets the maximum amount of uploaded files
Setheaderencoding (java.lang.String encoding): Setting the encoding format
Setprogresslistener (Progresslistener Plistener)
handling details of uploaded files
Chinese file garbled problem
File name Chinese garbled problem, can call Servletfileupload setheaderencoding method, or set request Setcharacterencoding property
Temporary file deletion problem
Because the file size exceeds the memory buffer size set by the Diskfileitemfactory.setsizethreshold method, the Commons-fileupload component saves the uploaded data using temporary files, so be sure to call Fileitem.delete when the program ends method to delete a temporary file.
The call to the Delete method must be after the stream has closed, otherwise the file consumption will occur, causing the deletion to fail.
File storage location
To ensure server security, upload files should be stored in the Web-inf directory of the application or in a directory that is not managed by the Web server.
To prevent multiple users from uploading files of the same file name, resulting in file coverage, file upload procedures should ensure that the upload file has a unique filename.
In order to prevent a single directory of too many files, affecting the speed of file reading and writing, processing upload files should be based on the total number of files uploaded, select the appropriate directory structure generation algorithm, will upload files distributed storage.
Progresslistener Show Upload Progress
Progresslistener Progresslistener = new Progresslistener () {
public void update (long pbytesread, long pcontentlength, int pitems) {
System.out.println ("Up to Now," + pbytesread + "bytes have been uploaded, total size is"
+ pcontentlength);
}
};
Upload.setprogresslistener (Progresslistener);
Show upload progress in KB
Long temp =-1; Temp Note set to class variable
Long ctemp = pbytesread/1024;
if (mBytes = = ctemp)
Return
temp = mBytes; File upload Case
Implementation steps
1. Create Diskfileitemfactory object, set buffer size and temp file directory
2. Create the Servletfileupload object using the Diskfileitemfactory object and set the size limit of the uploaded file.
3. Call the Servletfileupload.parserequest method to parse the request object and get a list object that holds all the uploaded content.
4, the list of iterations, each iteration of a Fileitem object, call its Isformfield method to determine whether the file is uploaded
is a normal form field, then the GetFieldName, GetString method is invoked to get the fields name and field values
To upload the file, call the getInputStream method to get the data input stream to read the uploaded data.
The specific code is as follows: try{ //1 Create a parser factory diskfileitemfactory factory=new diskfileitemfactory () ; //Get temporary file path string temppath=this.getservletcontext (). Getrealpath ("/temp"); Factory.setrepository (New file (TempPath)); //2. Get a parser servletfileupload upload=new servletfileupload (Factory); upload.setheaderencoding ("UTF-8"); // 3. The request will be passed in to the parser, parsing the request List<fileitem> list=upload.parserequest (Request); //4. Iteration List collection, get data for each entry for (fileitem item:list) { //5. Determine the type of item if (Item.isformfield ()) { //Normal input &NBSP;&N Bsp String inputname=item.getfieldname (); //string inputvalue=item.getstring ("UTF-8"); equivalent to the bottom two sentences STring inputvalue=item.getstring (); inputvalue= new string ( Inputvalue.getbytes ("Iso8859-1"), "UTF-8"); System.out.println (inputname+ "=" +inputvalue); }else{ //Uploading entry string Filename=item.getname ()///Get filename if (!filename.equals ("")) { filename=filename.substring (Filename.lastindexof ("\") +1); String savename=this.genera Tefilename (fileName); Inputstream in=item.getinputstream ();   string savepath= ""; save Path=this.getservletcontext () Getrealpath ("Web-inf/upload"); string savepaths=this.generatefilepath (savepath,savename) ; &NBSP;F Ileoutputstream out=new fileoutputstream (savepaths+ "\" +savename); byte[]& nbsp;buf=new byte[1024]; & nbsp int len=0; [ & nbsp while (Len=in.read (BUF) >0) { & nbsp Out.write ( Buf,0,len); &NB Sp } &NBSP ; in.close (); & nbsp out.close (); &N Bsp item.delete ()//delete temporary files & nbsp } } &NBS P Request.setattribute ("message", "upload success"); } }catch (exception e) { E.printstacktrace (); Request.setattribute ("message", "Upload failed"); } request.getrequestdispatcher ("/message.jsp"). Forward ( Request, response); }
Public string generatefilename (string filename) { Return uuid.randomuuid (). toString () + "_" +filename; } Public string generatefilepath (string path,string filename) { Int dir1 =filename.hashcode () & 0xf; & nbsp Int dir2 = (Filename.hashcode () >>4) &0xf; string savepath = path+ "\" +dir1+ "\" +dir2; File f = new file (Savepath); & nbsp if (!f.exists ()) { F.mkdirs ( ); }&NBSP;&Nbsp; return savepath; } Public void dopost (httpservletrequest request, httpservletresponse Response) throws servletexception, ioexception { doget (request, response); }
[Java] view plain copy//uploadservlet.java package com.hbsi.servlet ; import java.io.file; import java.io.fileoutputstream; import java.io.ioexception; import java.io.inputstream; import java.util.list; import java.util.uuid; import javax.servlet.servletexception; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import org.apache.commons.fileupload.fileitem; import org.apache.commons.fileupload.disk.diskfileitemfactory; import org.apache.commons.fileupload.servlet.servletfileupload; public class uploadservlet extends httpservlet { &nbsP