Apache FileUpload Introduction

Source: Internet
Author: User
Tags character set file size file upload tomcat server stringbuffer
Apache FileUpload Components

In the initial HTTP protocol, there is no feature to upload files. RFC1867 ("form-based File Upload in HTML") adds this functionality to the HTTP protocol. Client-side browsers, such as Microsoft IE, Mozila, Opera, etc., follow this specification to send user-specified files to the server. Server-side web-based programs, such as PHP, ASP, JSP, etc., can be in accordance with this specification, the user sent to resolve the file.

1.1, the client

Simply put, the RFC1867 specification requires the HTTP protocol to add a file type input tag to browse for files that need to be uploaded. The Enctype property of the form form is also required to be set to "Multipart/form-data", the method property is set to "POST", the following is our article.
Form code for the upload page:

<form action= "<%=request.getcontextpath ()%>/upload3servlet" 
 method= "post" enctype= 
 "multipart/ Form-data ">
file1:<input type=" file "name=" file "/><br/>
desc:<input type=" text "Name=" Desc "/><br/>
<input type=" Submit "value=" Submission "/>
</form>

1.2, server-side
A file upload request message entity consists of a series of items (text parameters and file parameters) encoded according to RFC1867 ("form-based file Upload in HTML".) It is cumbersome to program yourself to parse the data, and to understand the RFC1867 specification's knowledge of the encoding of the requested data. FileUpload can help us resolve such requests by encapsulating each item as an object that implements the Fileitem interface and returns it as a list. So, we just need to understand how the FileUpload API can be used, regardless of their underlying implementation.
Let's look at a simple File upload processing code:

Package cn.itcast.servlet;
Import Java.io.File;
Import java.io.IOException;
Import java.util.List;
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;
Import Org.apache.commons.io.FileUtils;  /** * File Upload * @author <a href= "mailto:wj@itcast.cn" > Wang Jian </a> * * public class Uploadservlet extends HttpServlet {@SuppressWarnings ("unchecked") public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {diskfileitemfactory f = new diskfileitemfactory ();//Disk Object F.setrepository (new File ("d:/a
"));
Set TEMP directory F.setsizethreshold (1024*8); 8k buffer, file greater than 8K is saved to the temp directory servletfileupload upload = new servletfileupload (f);//declares the object that resolves the request Upload.setheaderencodiNg ("UTF-8"); Processing file name Chinese Upload.setfilesizemax (1024 * 1024 * 5);//Set each file to a maximum of 5M upload.setsizemax (1024 * 1024 * 10);//upload up to 10M String p Ath = Getservletcontext (). Getrealpath ("/imgs");//Get the file to save the directory try {list<fileitem> list = Upload.parserequest ( request);//parsing for (Fileitem ff:list) {if (Ff.isformfield ()) {String ds = ff.getstring ("UTF-8");//Handling Chinese System.err.prin TLN ("description is:" + DS);} else {String SS = Ff.getname (); ss = Ss.substring (Ss.lastindexof ("\ \") + 1);//Parse file name Fileutils.copyinputstreamtofile (//Direct
Use Commons.io.FileUtils Ff.getinputstream (), new File (path + "/" + ss));
}}} catch (Exception e) {e.printstacktrace ();}} }

1.3. Fileitem interface
Org.apache.commons.fileupload.disk.DiskFileItem implements the Fileitem interface, which encapsulates data for individual form field elements. The data for related form field elements can be obtained by calling the method defined by Fileitem. We do not need to be concerned with the implementation of Diskfileitem, where the Fileitem interface type can be used to reference and access Diskfileitem objects. The Fileitem class also implements the Serializable interface to support serialization operations.

common methods of the Fileitem class:

1. Boolean Isformfield () method
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.

2. String getName () method

The GetName method is used to get the file name in the File upload field, the FileName property value in the form Field element description header, such as "C:\Documents and Settings\All Users\Documents\My pictures\ sample picture \ Sunset.jpg ". If the Fileitem class object corresponds to a normal form field, the GetName method returns NULL. Even if the user does not pass any of the file fields in the Web Form
File, but as long as the Name property of the File Form field is set, the browser also passes the information of the file fields to the server, except that the file name and the contents 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 "", Readers should be aware of this when calling Apache file upload components.
Note: The above packet is submitted via IE, so it is the full path and name. Such as
C:\Documents and Settings\All Users\Documents\My Pictures\ Example Picture \sunset.jpg. If other browsers, such as Firefox and chromium, are just names, no paths, such as sunset.jpg.

3. String getfieldname () method
The GetFieldName method is used to return the Name property value of the form Field element description header, which is also the value of the form label Name property. For example, "File1" in "Name=file1".

4. Void write (File file) 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.

5. String getString () method
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 () method
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 () method
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 () 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 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 () method
Returns the data content of the uploaded file in the form of a stream.

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

1.4, Diskfileitemfactory

This class encapsulates each item in the request message entity into a separate diskfileitem (implementation of the Fileitem interface) object that is implemented by the default implementation of 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).
Properties:
1) public static final int default_size_threshold:
Save 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 java.io.tmpdir by System Properties
Get. Code: System.getproperty ("Java.io.tmpdir");

3) Private int sizethreshold:
The critical value for saving the file in memory or the 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.

Other methods:
1, Fileitem CreateItem () method
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.

2, 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
Very 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 is stored directly in memory performance will be better.

3, Setsizethreshold
The 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.

4, 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 this method is not called 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");
Tomcat system Default temp directory is "

Package cn.itcast.servlet;
Import Java.io.File;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.InputStreamReader;
Import Java.util.Scanner;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import Org.apache.commons.fileupload.FileItemIterator;
Import Org.apache.commons.fileupload.FileItemStream;
Import org.apache.commons.fileupload.FileUploadException;
Import Org.apache.commons.fileupload.disk.DiskFileItemFactory;
Import Org.apache.commons.fileupload.servlet.ServletFileUpload;
Import Org.apache.commons.io.FileUtils; /** * Fileitemstream Example * @author <a href= "mailto:wj@itcast.cn" > Wang Jian </a> * @version 1.0 2012-3-15 */public C Lass Upload3servlet extends HttpServlet {public void DoPost (HttpServletRequest request, httpservletresponse response) th
Rows Servletexception, IOException {Long start = System.currenttimemillis (); String Path = Getservletcontext (). Getrealpath ("/imgs");
Diskfileitemfactory factory = new Diskfileitemfactory ();
Factory.setsizethreshold (1024 * 8);//Set 8k cache space Factory.setrepository (new File ("d:/a"));
Servletfileupload upload = new Servletfileupload (factory);
Upload.setheaderencoding ("UTF-8");//Set file name processing Chinese code try {fileitemiterator FII = upload.getitemiterator (request);//Use traversal class
while (Fii.hasnext ()) {Fileitemstream FIS = Fii.next (); if (Fis.isformfield ()) {//fileitemstream also use OpenStream to get the value of a normal form
InputStreamReader in = new InputStreamReader (Fis.openstream (), "UTF-8");
Scanner sc = new Scanner (in);
StringBuffer sb = new StringBuffer ();
if (Sc.hasnextline ()) {Sb.append (Sc.nextline ());} System.err.println ("Desc:" +sb.tostring ());}
else {String filename = fis.getname (); filename = filename. substring (filename.lastindexof ("\ \") + 1);
System.err.println ("File name:" + fileName);
InputStream in = Fis.openstream ();
Fileutils.copyinputstreamtofile (in, New File (path+ "/" +filename)); }}} catch (Fileuploadexception e) {e.printstacktrace ();} Long end = System.currenttimemillis (); System.err.println ("spents:" + (End-start));}}

1.7. Filecleanercleanup Cleanup Resources

Applies only to situations where you use Diskfileitem. In other words, they are stored in a temporary file before you process the uploaded data.
These temporary files are better when they are no longer being used (if the corresponding java.io.File are recyclable) will be deleted automatically. This is performed silently by a reap thread that is started by an instance of Org.apache.commons.io.FileCleaningTracker.

Your web app should use an instance of Org.apache.commons.fileupload.FileCleanerCleanup. That's simple, you just add it to your XML:

<listener>
  <listener-class>org.apache.commons.fileupload.servlet.filecleanercleanup</ Listener-class>
  </listener>

Then, after the diskfileitemfactory has been created, set up the resource collection:
Diskfileitemfactory f = new diskfileitemfactory ();//declaring temporary file object
F.setfilecleaningtracker (Filecleanercleanup.getfilecleaningtracker (This.getservletcontext ()));
F.setsizethreshold (1024*8);
Set the maximum number of bytes that can be placed in memory, and if this byte is exceeded, save it to the pro file.
F.setrepository (New File ("d:/a"));
Set TEMP directory

Note: The tomcat server must be shut down gracefully. Because this thread invokes the code that empties the temporary file when Tomcat terminates.
Normal shutdown refers to the execution of the Catalina_home\bin\shutdown.bat file.

1.8. Progress Progresslistener
This progress bar is more appropriate to monitor the progress in the background, if the upload progress, or use Ajax more appropriate:
Example code:

Upload.setprogresslistener (New Progresslistener () {
double dd = 0;
Long len = 0;
Parameter 1: Number of uploads completed
//Parameter 2: Total length
//Parameter 3: The first few elements start from 1. 0 for no public
void update (Long pbytesread, long pcontentlength, int pitems) {
double persent = Pbytesread*100/pcont Entlength;
if (dd!=persent) {
System.err.println (dd+ "%");
dd=persent;
} else if (persent==100) {
System.err.println ("100%");}}
);

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.