Apache Jakarta project: commons fileupload User Guide

Source: Internet
Author: User

I have been focusing on file upload in recent times, and it is always inappropriateCodeYou can't write any good things at your own level.
Until now. Today, I saw a brief introduction to commons fileupload on Google. I will go to Apache Jakarta right away.
Project. Haha ...... That's it ~
It took an hour to read its E-text overview. I thought it was too convenient to use it. Just a few words would work.
It's a good deal to complete the upload operation, so I can be a little lazy: P. In the afternoon, I wrote a simple bean to test the use of key classes in the bean, and learned more about the results of its method. Then
E-document user guide. It should be helpful for uploading files on pages.

Using fileupload
Use fileupload

Fileupload
Can be used in a number of different ways, depending upon
Requirements of your application. In the simplest case, you will call
Single Method to parse the Servlet request, and then process the list
Of items as they apply to your application. At the other end of
Scale, you might decide to customize fileupload to take full control
The way in which individual items are stored; for example, you might
Decide to stream the content into a database.
Fileupload can be based on the ApplicationProgramRequirements
It can be used in many different places. For example, you may call a simple method to compile servlet requests and use these projects as part of your application. From the other party
In other words, you may want to customize fileupload to store all projects. In another example, you may want to stream the content and store it in the database.

Here, we
Will describe the basic principles of fileupload, and revoke strate some
Of the simpler-and most common-usage patterns. customization
Fileupload is described elsewhere.
Here we will introduce the basic usage principles of fileupload and describe some simple and common usage modes. The introduction to fileupload customization is discussed elsewhere (in fact there is nothing.

How it works
Introduction

A
File Upload request comprises an ordered list of items that are encoded
According to RFC 1867, "form-based file upload in HTML". fileupload
Can parse such a request and provide your application with a list
The individual uploaded items. Each such item implements t he fileitem
Interface, regardless of its underlying implementation.
An upload request consists of a seriesArticleI have already put it in the HTML directory of my blog favorites. Fileupload can compile such requests and pass these personalized upload projects to your applications. Every such project implements the fielitem interface, no matter how it is implemented.

Each
file item has a number of properties that might be of interest for your
application. for example, every item has a name and a content type, and
can provide an inputstream to access its data. on the other hand, you
may need to process items differently, depending upon whether the item
is a regular form field-that is, the data came from an ordinary text
box or similar html Field-or an uploaded file. the fileitem interface
provides the methods to make such a determination, and to access the
data in the most appropriate manner.
each file project has its own attributes, which may be of interest to your application
. For example, each project has a name and content type, and an input stream can be provided to access the written data. On the other hand, you may need to deal with different projects in different ways, which
depends on whether the project is a normal word field, that is, the data comes from a common text box, HTML-like word field, or an uploaded file. The fileitem interface provides some methods to
make such a decision and use the most appropriate method to access the data.

Fileupload creates new file items
Using a fileitemfactory. This is what gives fileupload most of its
Flexibility. The factory has ultimate control over how each item is
Created. The default factory stores the item's data in memory or on
Disk, depending on the size of the item (I. e. bytes of data). However,
This behavior can be customized to suit your application.
Fileupload
Use fileitemfactory to create a new file project. This is completely feasible for fileupload. The factory is the only tool that controls the creation of each project. Default
The data of the factory storage project is stored in the memory or hard disk, which depends on the project size (for example, the Data byte array ). However, you can define it as suitable for your application.

Parsing the request

Before
You can work with the uploaded items, of course, you need to parse
Request itself. Ensuring that the request is actually a File Upload
Request is straightforward, but fileupload makes it simplicity itself,
By providing a static method to do just that.
Before using the upload project, you need to compile the request. The most important thing is to confirm that the request actually comes from File Upload, but fileupload uses a static method to simplify itself.

// Check that we have a file upload request
Boolean ismultipart = fileupload. ismultipartcontent (request );

Now we are ready to parse the request into its constituent items.
Now we can prepare to start compiling the request.

The simplest case
Simple Example

The simplest usage scenario is the following:
> Uploaded items shocould be retained in memory as long as they are reasonably small.
> Larger items shocould be written to a temporary file on disk.
> Very large upload requests shoshould not be permitted.
>
Built-in defaults for the maximum size of an item to be retained in
Memory, the maximum permitted size of an upload request, and
Location of temporary files are acceptable.

The following are some simple application scenarios:
> As long as the upload project is small enough, it should be kept in the memory.
> Large projects should be written in temporary files on the hard disk.
> Avoid large upload requests.
> Restrict the space occupied by the project in memory, restrict the maximum upload requests, and set the location of temporary files.

Handling a request in this scenario couldn't be much simpler:
The process for this scenario is simple:

// Create a new file upload Handler
Diskfileupload upload = new diskfileupload ();
// Parse the request list
/* Fileitem */items = upload. parserequest (request );

That's all that's needed. Really!
This is all the code we need!

The
Result of the parse is a list of file items, each of which implements
The fileitem interface. processing these items is discussed below.
The compilation result is a series of file projects, each of which implements a fileitem interface. The following describes how to deal with this write project.

Exercising more control
Control exercise

If
Your usage scenario is close to the simplest case, described abve,
You need a little more control over the size thresholds or the location
Of temporary files, you can customize the behavior using the methods
The diskfileupload class, like this:
If your application scenario is very similar to the simplest example, but you need a little more extension control, including the size limit or temporary file settings, you can customize the behavior through the diskfileupload class method, such:

// Create a new file upload Handler
Diskfileupload upload = new diskfileupload ();
// Set upload Parameters
Upload. setsizethreshold (yourmaxmemorysize );
Upload. setsizemax (yourmaxrequestsize );
Upload. setrepositorypath (yourtempdirectory );
// Parse the request list
/* Fileitem */items = upload. parserequest (request );

Of
Course, each of the configuration methods is independent of the others,
But if you want to configure them all at once, you can do that with
Alternate parserequest () method, like this:
Of course, each configuration method is independent of any other one, but if you want to configure them at one time, you can use another method of parserequest () to reload it, like this:

// Create a new file upload Handler
Diskfileupload upload = new diskfileupload ();
// Parse the request list
/* Fileitem */items = upload. parserequest (request, yourmaxmemorysize, yourmaxrequestsize, yourtempdirectory );

Shocould
You need further control over the parsing of the request, such
Storing the items elsewhere-for example, in a database-you will
Need to look into customizing fileupload.
If you want to use more controls, such as Storing Projects to other places (such as databases), you can view the custom fileupload (this connection is a false, empty page) introduction.

Processing the uploaded items
Process uploaded Projects

Once
The parse has completed, you will have a list of file items that you
Need to process. In most cases, you will want to handle file uploads
Differently from regular form fields, so you might process the list
Like this:
Once the compilation is complete, you will get a list of file projects to be processed. In many cases, you want to process each specific project separately. Therefore, you can do this:

// Process the uploaded items
Iterator iter = items. iterator ();
While (ITER. hasnext ())
{
Fileitem item = (fileitem) ITER. Next ();
If (item. isformfield ())
{
Processformfield (item );
}
Else
{
Processuploadedfile (item );
}
}

For
A regular form field, you will most likely be interested only in
Name of the item, and its string value. As you might CT, accessing
These is very simple.
For common form fields, you may be interested in the project name. It's really easy to fulfill your needs, as shown below:

// Process a regular form field
If (item. isformfield ())
{
String name = item. getfieldname ();
String value = item. getstring ();...
}

For
A file upload, there are several different things you might want
Know Before you process the content. Here is an example of some of
Methods you might be interested in.
There are many differences between uploading files ~ You may want to know more. The following is an example, which contains many interesting methods.

// Process a File Upload
If (! Item. isformfield ())
{
String fieldname = item. getfieldname ();
String filename = item. getname ();
String contenttype = item. getcontenttype ();
Boolean isinmemory = item. isinmemory ();
Long sizeinbytes = item. getsize ();
...
}

With
Uploaded files, you generally will not want to access them via memory,
Unless they are small, or unless you have no other alternative. Rather,
You will want to process the content as a stream, or write the entire
File to its ultimate location. fileupload provides simple means
Accomplishing both of these.
For an uploaded file, you certainly do not want to always access it through the memory unless it is small, or you have no choice. You really want to use a stream to process the file content or write the object to its final address. Fileupload provides a simple way to meet two requirements.

// Process a File Upload
If (writetofile)
{
File uploadedfile = new file (...);
Item. Write (uploadedfile );
}
Else
{
Inputstream uploadedstream = item. getinputstream ();
...
Uploadedstream. Close ();
}

Note
That, in the default Implementation of fileupload, write () will attempt
To rename the file to the specified destination, if the data is already
In a temporary file. Actually copying the data is only done if
Rename fails, for some reason, or if the data was in memory. If you do
Need to access the uploaded data in memory, you need simply call
Get () method to obtain the data as an array of bytes.

Note: In
In the default Implementation of fileupload, The wirte () method should be worth noting. If the data is still not removed from a temporary file, this method will try to rename the file as the target file.
. In fact, if the rename fails, the data will only be copied. If you need to access the uploaded data in the memory, you can use the get () method to obtain the binary array of the data.

// Process a file upload in memory
Byte [] DATA = item. Get ();...

What's next
What to do next

Hopefully
This page has provided you with a good idea of how to use fileupload in
Your own applications. For more detail on the methods introduced here,
As well as other available methods, you should refer to the javadocs.
I hope this article will help you with fileupload. For more details, read the related documents.

The
Usage described here shoshould satisfy a large majority of File Upload
Needs. However, shocould you have more complex requirements, fileupload
Shocould still be able to help you, with it's flexible mizmization
Capabilities.
This introduction should be enough to meet most of your needs. However, if you have more complex requirements, you need to customize suitable feasible solutions.

The user guide has been roughly translated here. I just started to learn how to use this toolkit, and it is inevitable that there will be deviations in understanding it, I will also improve some details with the specific use (no way, the official website does not have this introduction, but I can only find it myself, haha ).

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.