Details and use of files uploaded to the tomcat server Commons-fileupload

Source: Internet
Author: User

Three classes: Diskfileupload, Fileitem and Fileuploadexception. All three of these classes are in the Org.apache.commons.fileupload package.

First, you need to explain the Enctpye properties of the form table:

The meaning of enctype= "Multipart/form-data" in the form is to set the MIME encoding of the form. By default, this encoding format is application/x-www-form-urlencoded and cannot be used for file uploads, and only multipart/form-data is used to complete the transfer of file data.
Do the following.
Enctype= "Multipart/form-data" is to upload binary data; The value of input in the form is passed in 2 binary ways.
The value of input in the form is passed through in 2, so the request is not valued. In other words, this code is added, and the request will be passed unsuccessfully.

Diskfileupload class

The Diskfileupload class is the core class of the Apache file upload component that the application developer uses to interact with the Apache file Upload component.

The following are some of the most important methods used in the Diskfileupload class.
1. Setsizemax method
The Setsizemax method is used to set the maximum allowable size of the request message entity content to prevent the client from intentionally uploading a large file to fill the server-side storage space in bytes.

The complete syntax is defined as follows:
public void Setsizemax (long Sizemax)
If the size of the entity content in the request message exceeds the set value of the Setsizemax method, the method throws a Fileuploadexception exception.
2. Setsizethreshold method
The Apache file upload component needs to temporarily save the parsed data when parsing and processing the contents of each field in the uploaded data.

Because the Java virtual machine can use the default memory space is limited (the author does not test 100M), the limit will occur when the "Java.lang.OutOfMemoryError" error,

If the uploaded file is large, such as uploading 800M files, in memory will not be able to save the contents of the file, the Apache file Upload component will use temporary files to save the data;

However, if you upload a file that is small, such as uploading a 600-byte file, it is obvious that it is more efficient to store it directly in memory.

The Setsizethreshold method is used to set whether the critical value of the parsed data is saved using a temporary file, and the unit of the parameter passed in is a byte. The complete syntax is defined as follows:
public void Setsizethreshold (int sizethreshold)
3. Setrepositorypath method
The Setrepositorypath method is used to set the storage directory for temporary files mentioned in the Setsizethreshold method, where absolute paths are required. The complete syntax is defined as follows:
public void Setrepositorypath (String repositorypath)
If you do not set the storage path, the temporary file will be stored in the directory specified by the JVM environment property "Java.io.tmpdir", and Tomcat 5.5.9 will set this property to the "<tomcat installation directory >/temp/" directory.
4. Parserequest method
The Parserequest method is an important method of the Diskfileupload class, which is an ingress method for parsing HTTP request messages.

If the type of the entity content in the request message is not "Multipart/form-data", the method throws a Fileuploadexception exception.

The Parserequest method 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. The complete syntax for the Parserequest method is defined as follows:
Public List parserequest (httpservletrequest req)
The Parserequest method also has an overloaded method that centralizes the functionality of all of the above methods, with the complete syntax defined as follows:
Parserequest (httpservletrequest req,int sizethreshold,long Sizemax,
String path)
These two parserequest methods will throw fileuploadexception exceptions.
5. Ismultipartcontent method
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 Diskfileupload class, and its complete syntax is defined as follows:
public static Final Boolean ismultipartcontent (HttpServletRequest req)
6. Setheaderencoding method
As the browser submits the form form, the text content of the normal form will be passed to the server, for the File upload field, in addition to the original file content, but also to pass the file path name and other information,

As shown in Figure 1.3 below. Whether the form form uses the "application/x-www-form-urlencoded" encoding or the "Multipart/form-data" encoding,

They are just a format that organizes the contents of individual form form field elements together, and these are represented by a character set encoding.

For information about what character sets the browser uses to encode content in form fields, see section 6.9.2 in the book "in-depth experience Java Web Development Insider-Core Basics", written by the author.

A form of type "Multipart/form-data" selects the character set encoding for the contents of a form field in the same way as a form with "application/x-www-form-urlencoded" type.

The text content in the form form and the file path name in the File upload field are in memory a byte array of their character set encoding, and when the Apache file Upload component reads the content,

It is necessary to know the character set encoding they use in order to convert them to the correct word literals return.
For the description header content of each form field that is passed to the Web server on the browser, the Apache file Upload component needs to convert them back into a string.

The Setheaderencoding method is used to set the character set encoding used in the conversion, the principle and the author's "in-depth experience Java Web Development Insider-Core Foundation" The Servletrequest.setcharacterencoding method described in 6th. 9.4 of the book is the same.

The complete syntax for the Setheaderencoding method is defined as follows:
public void setheaderencoding (String encoding)
Where the encoding parameter specifies the character set encoding used when translating the description header content of individual form fields into strings.
Note: If the reader is using the Apache file to upload the component when it encounters the problem of garbled characters, it is generally not the reason to call the Setheaderencoding method correctly.


Fileitem class
The Fileitem class is used to encapsulate the data for a single form field element, and a form field element corresponds to a Fileitem object, and the data for the related form field elements can be obtained by invoking the Fileitem object's method.

Fileitem is an interface, used in the application is actually an implementation class of the interface, the name of the implementation class is not important, the program can use the Fileitem interface type to reference and access, in order to facilitate the explanation,

Here the Fileitem implementation class is called the Fileitem class. The Fileitem class also implements the Serializable interface to support serialization operations.
For form forms with the "Multipart/form-data" type, the data for each form field element in the browser's uploaded entity content is split between the fields separated by the boundary line, and the content between the two dividing lines is called a partition.

The contents of each partition can be considered as two parts, one describing the form field elements, the other being the body content of the form field element, and 1.3.

Figure 1.3

The main part has two possibilities, either the form content that the user fills out or the content of the file. The Fileitem class object is actually the object that encapsulates the data of a partition in Figure 1.3, which internally uses two member variables to store the description header and the body content, where the variable that holds the principal content is an object of the output stream type. When the size of the principal content is less than the critical value set by the Diskfileupload.setsizethreshold method, the stream object is associated to a piece of memory and the principal content is stored in memory. When the data of the principal content exceeds the critical value set by the Diskfileupload.setsizethreshold method, the stream object is associated to a temporary file on the hard disk, and the principal content is saved to the temporary file. The storage directory for temporary files is set by the Diskfileupload.setrepositorypath method, and the temporary file name is in the format "upload_00000005 (eight-bit or more than eight digits). tmp" In this form, The Fileitem class internally provides a mechanism to maintain the value of the temporary file name in a way that guarantees the uniqueness of the temporary file name. When the application saves the principal content to a specified file, or when the Fileitem object is reclaimed by the garbage collector, or when the Java Virtual machine ends, the Apache file Upload component attempts to delete the temporary file to ensure that the temporary files are purged in a timely manner.
Here are a few common methods in the Fileitem class:
1. Isformfield method
The Isformfield method is used to determine whether the data encapsulated by the Fileitem class object belongs to a normal form field or to a file form field, and returns True if it is a normal form field, otherwise false. The complete syntax for this method is defined as follows:
public boolean Isformfield ()
2. GetName method
The GetName method is used to get the file name in the File Upload field, and for the description header shown in the third partition in Figure 1.3, the GetName method returns the string "C:\bg.gif". If the Fileitem class object corresponds to a normal form field, the GetName method returns NULL. Even if the user does not pass any files through the file fields in the Web form, the browser will pass information about the file fields to the server as long as the Name property of the File Form field is set, except that the file name and the content portion of the file are empty, but the form field still corresponds to a Fileitem object, at which point, The GetName method returns the empty string "", which the reader should consider when invoking the Apache file Upload component. The complete syntax for the GetName method is defined as follows:
Public String GetName ()
Note: If a user uploads a file using a Windows system, the browser will pass the full path to the file, and if the user uploads the file using Linux or a UNIX system, the browser will only pass the name portion of the file.
3. GetFieldName method
The GetFieldName method is used to return the Name property value of the form field element, which is the Name property value in the individual description header sections in Figure 1.3, such as "P1" in "Name=p1". The complete syntax for the GetFieldName method is defined as follows:
Public String GetFieldName ()
4. Write method
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. The complete syntax is defined as follows:
public void write (file file)
5. GetString method
The GetString method is used to return the principal content that is saved in the Fileitem object as a string, and it has two overloaded definition forms:
Public java.lang.String getString ()
Public java.lang.String getString (java.lang.String encoding)
Throwsjava.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. getContentType method
The getContentType method is used to obtain the type of the uploaded file, and for the description header shown in the third partition in Figure 1.3, the getContentType method returns the string "Image/gif", which is the value part of the "Content-type" field. If the Fileitem class object corresponds to a normal form field, the method returns NULL. The complete syntax for the getContentType method is defined as follows:
Public String getContentType ()
7. IsInMemory method
The IsInMemory method is used to determine whether the principal content encapsulated by the Fileitem class object is stored in memory or stored in a temporary file, and returns True if stored in memory, otherwise false. The complete syntax is defined as follows:
public boolean isinmemory ()
8. Delete method
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 the Apache component uses a variety of ways to clean up temporary files as quickly as possible, there is still a chance that temporary files will be permanently saved to the hard disk when there is an exception. In some cases, this method can be called to delete temporary files in a timely manner. The complete syntax is defined as follows:
public void Delete ()
Fileuploadexception class
During file upload, a variety of exceptions can occur, such as network outages, data loss, and so on. In order to handle the different exceptions properly, the Apache file Upload component also developed four exception classes, where Fileuploadexception is the parent class of other exception classes, and several other classes are just the underlying classes that are indirectly called, and for Apache component callers, Only the fileuploadexception exception class can be captured and processed.

Details and use of files uploaded to the tomcat server Commons-fileupload

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.