Commons-fileupload user guide

xiaoxiao2021-03-06  20

Using fileupload

FileUpload can be used in a number of different ways, depending upon the requirements of your application. In the simplest case, you will call a 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 the scale, you might decide to customize FileUpload to take full control of the way in which individual items are stored; for example, you might decide to stream the content into a database.

Here, We Well Describe The Basic Principles of FileUpload, And Illustrate Some of the Simpler - And Most Common - Usage Patterns. Customization of FileUpload is described elsewhere.

HOW it works

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 of the individual uploaded items. Each such item Implements The FileItem Interface, Regardless of Its Underlying Implementation.

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.

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 (IE Bytes of Data). HoWever, this Behavior Can Be Customized to Suit your application.parsing the request

Before you can work with the uploaded items, of course, you need to parse the 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.

// Check That We Have a file upload = fileupload.ismultipartcontent (request);

Now We are ready to parse The Request ITO ITS CONSTINT ITEMS.

The SimpleSt Case

THE SIMPLEST USAGE SCENARIO IS The FOLLOWING:

Uploaded items should be retained in memory as long as they are reasonably small. Larger items should be written to a temporary file on disk. Very large upload requests should not be permitted. The built-in defaults for the maximum size of an item to be Retained in Memory, The Maximum Permitted Size of An Upload Request, And The Location of Temporary Files Are Acceptable.

Handling a Request in this Scenario COULDN'T BE MUCH SIMPLER:

// Create a new file upload hand = new diskfileupload (); // parse the requestList / * fileItem * / items = upload.Parsequest (Request);

That's all what's needed. Really!

The Result of The Parse IS A List of File Items, Each of Which Implements The FileItem Interface. Processing these items is discussed Below.

Exercising more control

If your usage scenario is close to the simplest case, described above, but you need a little more control over the size thresholds or the location of temporary files, you can customize the behavior using the methods of the DiskFileUpload class, like this: // Create a new file upload handlerDiskFileUpload upload = new DiskFileUpload (); // Set upload parametersupload.setSizeThreshold (yourMaxMemorySize); upload.setSizeMax (yourMaxRequestSize); upload.setRepositoryPath (yourTempDirectory); // Parse the requestList / * FileItem * / items = Upload.Parsequest (Request);

Of Course, Each of the Configuration Methods Is Independent of The Others, But if you want to configure the all at once, you can do what with an alternate parse () method () Method, LIKE THIS:

// Create a new file upload handlerDiskFileUpload upload = new DiskFileUpload (); // Parse the requestList / * FileItem * / items = upload.parseRequest (request, yourMaxMemorySize, yourMaxRequestSize, yourTempDirectory);

SHOULD You NEED FURTHER CONTROL OVER THE PARSING OF THE REQUEST, Such As Storing The Items Elsewhere - for Example, In A Database - You Will Need To Look Into Customizing FileUpload.

Processing the uploaded items

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.:

// process the uploaded itemsiterator it = 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 the name of the item, and its String value. As you might expect, accessing these is very simple.// Process a regular form fieldif (item.isFormField ()) {String name = item.getfieldname (); string value = item.getstring (); ...}

For A File Upload, There Area SEVERAL DIFFERENT THINGS You Might Want To Know Before You Process The Content. Here IS An Example of Some of the Methods You Might Be Interested in.

// Process a file uploadif (! 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 them via access 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 of Accomplishing Both of these.

// Process a file uploadif (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 the the rename fails, for some reason , or if the data.

IF you do need to access the uploaded data in memory, you need simply call the get () method to obtain the data as an array of bytes.

// process a file upload in membratebyte [] data = item.get (); ... interaction with Virus Scanners

Virus scanners running on the same system as the web container can cause some unexpected behaviours for applications using FileUpload. This section describes some of the behaviours that you might encounter, and provides some ideas for how to handle them.

The default implementation of FileUpload will cause uploaded items above a certain size threshold to be written to disk As soon as such a file is closed, any virus scanner on the system will wake up and inspect it, and potentially quarantine the file -. That is , move it to a special location where it will not cause problems. This, of course, will be a surprise to the application developer, since the uploaded file item will no longer be available for processing. On the other hand, uploaded items below that same threshold will be held in memory, and therefore will not be seen by virus scanners. This allows for the possibility of a virus being retained in some form (although if it is ever written to disk, the virus scanner would locate and inspect it) .

One commonly used solution is to set aside one directory on the system into which all uploaded files will be placed, and to configure the virus scanner to ignore that directory. This ensures that files will not be ripped out from under the application, but then leaves responsibility for virus scanning up to the application developer. Scanning the uploaded files for viruses can then be performed by an external process, which might move clean or cleaned files to an "approved" location, or by integrating a virus scanner within the application itself. THE DETAILS OF Configuring An External Process Or Integrating Virus Scanning Into An Application Are Outside The Scope of this Document.What's 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.

The usage described here should satisfy a large majority of file upload needs. However, should you have more complex requirements, FileUpload should still be able to help you, with it's flexible customization capabilities.

转载请注明原文地址:https://www.9cbs.com/read-46554.html

New Post(0)