File Upload: Fileitem class, Servletfileupload class, Diskfileitemfactory class

Source: Internet
Author: User

File Upload:

Servletfileupload is responsible for processing the uploaded file data and encapsulating each entry in the form into a single Fileitem object. When you use a Servletfileupload object to resolve a request, you need to decide whether to save the parsed data in memory or in a temporary file based on the properties of the Diskfileitemfactory object Sizethreshold (critical value) and repository (temporary directory) , if it is a temporary file, in which temporary directory is saved?. Therefore, we need to construct the Diskfileitemfactory object before parsing, by constructing the Servletfileupload object or Setfileitemfactory () The Servletfileupload method sets the Fileitemfactory property of the object.

Fileitem class

The HTML page input must have name <input type= "file" name= "filename" >

The form's Enctype property must be set to Multipart/form-data if it contains a file on which the entry is transferred.

<form action = "/day16/servlet/uploadservlet" enctype= "Multipart/form-data" method= "POST" >

If the browser form is Multipart/form-data, then when the browser submits the form data, it will encapsulate the data with the MIME protocol, and the server will not be able to use the

The original traditional Fang get the data. The server side wants to get the data through the stream. The request provides a getinputstream read stream.

Common methods of the Fileitem class:

1. Boolean Isformfield ()

The Isformfield method is used to determine whether the data encapsulated by the Fileitem class object is a plain text form field or a file form field that returns true if it is a normal form field, otherwise false. As a result, you can use this method to determine whether a form field is normal or a file is uploaded.

2. String GetName ()
The GetName method is used to obtain the file name in the File upload field.

Note that the file name obtained in IE or Firefox is not the same, IE is the absolute path, Firefox is just the file name.

3. String GetFieldName ()
The GetFieldName method is used to return the value of the form label Name property. As in the example above, <input type= "text" name= "column"/> value.

4. Void write (file file)

The Write method is used to save the principal content saved in the Fileitem object to a specified file. If the principal content in the Fileitem object is saved in a temporary file, the temporary file may be purged after the method has completed successfully. This method can also write the contents of a normal form field to a file, but its main purpose is to save the uploaded file contents to the local file system.

5. String getString ()
The GetString method is used to return the contents of the data stream stored in the Fileitem object as a string, which has two overloaded definition forms:

Public Java.lang.String getString ()

Public java.lang.String getString (java.lang.String encoding)

Throws Java.io.UnsupportedEncodingException

The former uses the default character set encoding to convert the principal content to a string, which uses the character set encoding specified by the parameter to convert the principal content to a string. If the Chinese garbled behavior occurs when reading the contents of a normal form field element, call the second GetString method and pass the correct character set encoding name for it.

6. String getContentType ()
The getContentType method is used to obtain the type of the uploaded file, that is, the form field element that describes the value of the header attribute "Content-type", such as "Image/jpeg". If the Fileitem class object corresponds to a normal form field, the method returns NULL.

7. Boolean isinmemory ()
The IsInMemory method is used to determine whether the data content encapsulated by the Fileitem object is stored in memory or stored in a temporary file, and returns True if stored in memory, otherwise false.

8. void Delete ()
The Delete method is used to empty the body contents of the Fileitem class object, and if the principal content is saved in a temporary file, the Delete method deletes the temporary file.

Although temporary files are automatically purged when the Fileitem object is collected by the garbage collector, a timely call to the Delete method can purge temporary files earlier and free up system storage resources. In addition, when the system is abnormal, it is still possible to cause temporary files to be permanently saved on the hard disk.

9. InputStream getInputStream ()
Returns the data content of the uploaded file in the form of a stream.

Ten. Long GetSize ()
Returns the size, in bytes, of the uploaded file.


To facilitate user processing of file upload data, Apache Open source organization provides an open source component (commons-fileupload) for processing form file uploads. Using the Commons-fileupload component for file uploads, The appropriate jar package for the component needs to be imported.

Commons-fileupload and Commons-io two jar packages.

Diskfileitemfactory is the factory that creates the Fileitem object, including the method:

1.public void Setsizethreshold (Int?sizethreshold)
Set the size of the memory buffer, the default value is 10K, if the file is greater than 10K, the temporary file will be used

Save the upload file.

2.public void Setrepository (Java.io.File repository)
Specifying temporary file directories

3.public diskfileitemfactory ();

Servletfileupload class

Servletfileupload is responsible for processing the uploaded file data and encapsulating each entry in the form into a single Fileitem object.

The Org.apache.commons.fileupload.servlet.ServletFileUpload class is the core advanced class of the Apache file upload component that handles file uploads (so-called advanced is an easy-to-use interface that does not require a bottom-level implementation and exposes users).

Use its parserequest (HttpServletRequest) method to encapsulate the data submitted through each HTML tag in the form into a Fileitem object, and then return as a list of lists. Using this method to handle uploading files is simple and easy to use.

If you want to further improve your new energy, you can use the Getitemiterator method to directly get the data input stream for each file entry and directly process the data.

When you use a Servletfileupload object to resolve a request, you need to decide whether to save the parsed data in memory or in a temporary file based on the properties of the Diskfileitemfactory object Sizethreshold (critical value) and repository (temporary directory) , if it is a temporary file, in which temporary directory is saved?. Therefore, we need to construct the Diskfileitemfactory object before parsing, by constructing the Servletfileupload object or Setfileitemfactory () The Servletfileupload method sets the Fileitemfactory property of the object.

Common methods of the Servletfileupload class:
1) public void Setsizemax (long Sizemax)
The Setsizemax method inherits from the Fileuploadbase class, which sets the maximum size limit for requesting message entity content (that is, all uploaded data) to prevent clients from maliciously uploading large files to waste server-side storage space. The argument is a long number in bytes.

In the process of request parsing, if the size of the request message body content exceeds the set value of the Setsizemax method, the Fileuploadbase internally defined Sizelimitexceededexception exception will be thrown ( Sub-class of fileuploadexception). The method has a corresponding Read method: public long GetSizeMax () method.

2) public void Setfilesizemax (long Filesizemax)
The Setfilesizemax method inherits from the Fileuploadbase class, which sets the maximum size limit for a single upload file to prevent clients from maliciously uploading large files to waste server-side storage space. The argument is a long number in bytes. The method has a corresponding Read method: public long Gefilesizemax () method.

In the process of request parsing, if the size of a single upload file exceeds the set value of the Setfilesizemax method, the Fileuploadbase internally defined Filesizelimitexceededexception exception will be thrown ( Sub-class of fileuploadexception).

3) Public List parserequest (javax.servlet.http.HttpServletRequest req)
The Parserequest method is an important method of the Servletfileupload class, which is an entry method for parsing the content of the HTTP request message body. It parses the data for each field in the form form, wraps them into separate Fileitem objects, and then returns those Fileitem objects into a Collection object of type list.

This method throws a Fileuploadexception exception to handle various exceptions such as the file size is too large, the type of the entity content in the request message is not "Multipart/form-data", the IO exception, the request message body length information is missing, and so on. Each type of exception is a subtype of fileuploadexception.

4) Public Fileitemiterator Getitemiterator (HttpServletRequest request)
The Getitemiterator method and the Parserequest method are basically the same. But the Getitemiterator method returns an iterator that holds not the Fileitem object, but the Fileitemstream object, and if you want to further improve the new energy, you can use the Getitemiterator method, Get the data input stream of each file item directly, do the bottom processing; if performance is not a problem, you want the code to be simple, then use the Parserequest method.

5) Public STIATC Boolean ismultipartcontent (HttpServletRequest req)
The Ismultipartcontent method method is used to determine whether the content in the request message is a "multipart/form-data" type, or True to return false. The Ismultipartcontent method is a static method that can be called without creating an instance object of the Servletfileupload class.

6) Getfileitemfactory () and Setfileitemfactory (fileitemfactory)
The FileUpload method inherits from the class, which is used to set and read the Fileitemfactory property.

7) public void Setprogresslistener (Progresslistener plistener)
Sets the file upload Progress listener. The method has a corresponding Read method: Progresslistener Getprogresslistener ().

8) public void setheaderencoding ()
In the message body of the file upload request, in addition to the normal form field value is the text content, the file path name in the upload file is also the text (including the file name), in memory is one of their character set encoding byte array, the Apache file Upload component When reading these content, It is necessary to know the character set encoding they use in order to convert them to the correct word literals return.

The Setheaderencoding method inherits from the Fileuploadbase class and is used to set the character encoding mentioned above. If not set, the corresponding Read method Getheaderencoding () method returns null, using the character encoding of the HttpServletRequest setting, if the HttpServletRequest character encoding is also null. The system default character encoding is used. The system default character encoding can be obtained through a statement:

System.getproperty ("file.encoding"));

Diskfileitemfactory class

A task that encapsulates each item in the request message entity into a separate diskfileitem (implementation of the Fileitem interface) object
Default implementation by the Org.apache.commons.fileupload.FileItemFactory interface
Org.apache.commons.fileupload.disk.DiskFileItemFactory to finish. When the uploaded file item is compared to the hour, it is saved directly in memory (faster), relatively large, in the form of temporary files, saved in the disk temporary folder (although slower, but memory resources are limited).

Property
1) public static final int default_size_threshold: Saves the file in memory or the disk Temp folder's default threshold value of 10240, which is 10kb.

2) Private file repository: Used to configure the temporary folder that is used when the file item is larger than the critical value when the file project is created, default to the system default temporary file path, which can be obtained through the system Properties Java.io.tmpdir. The following code:

System.getproperty ("Java.io.tmpdir");

3) Private int sizethreshold: The critical value for saving the file in memory or disk Temp folder

Construction method
1) public diskfileitemfactory ()

The file item factory object is constructed with the default thresholds and the system Temp folder.

2) public diskfileitemfactory (int sizethreshold,file repository)

Use parameters to specify the critical value and the system Temp folder to construct the file item factory object.

3) Fileitem CreateItem ()
Each request message entity project is built into an Diskfileitem instance and returned according to the Diskfileitemfactory-related configuration. This method never needs to be called by us personally, and the FileUpload component is used internally when parsing the request.

4) void Setsizethreshold (int sizethreshold)
Apache File Upload Component when parsing the contents of each field in the uploaded data, it is necessary to temporarily save the parsed data for further processing of the data later (either in a disk-specific location or into a database). Because the Java virtual machine can use a limited amount of memory by default, a "Java.lang.OutOfMemoryError" error will be thrown when the limit is exceeded. If the uploaded file is large, such as 800M files, in memory will not be able to temporarily save the contents of the file, the Apache file Upload component to use temporary files to save the data, but if the uploaded file is small, such as 600-byte files, it is obvious that it will be stored directly in memory performance will be better.

The Setsizethreshold method is used to set whether the upload file is saved as a temporary file in the disk's critical value (int value in bytes), and the system default value of 10KB is applied if the method is not called to set this threshold. The corresponding Getsizethreshold () method is used to obtain this critical value.

5) void Setrepository (File repository)
The Setrepositorypath method is used to set the file to be stored as a temporary file in the storage directory on disk when the upload file size is greater than the critical value set by the Setsizethreshold method. There is a corresponding File getrespository () method that obtains a temporary folder.

Note: When you do not call this method to set the temporary file store directory, the default system default temporary file path is used, which can be obtained through the system Properties Java.io.tmpdir. The following code:

System.getproperty ("Java.io.tmpdir");

The Tomcat system default temp directory is "<tomcat installation directory >/temp/".

File Upload: Fileitem class, Servletfileupload class, Diskfileitemfactory class

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.