FileDocCategorySizeDatePackage
DefaultFileItem.javaAPI DocApache Tomcat 6.0.1418120Fri Jul 20 04:20:30 BST 2007org.apache.tomcat.util.http.fileupload

DefaultFileItem

public class DefaultFileItem extends Object implements FileItem

The default implementation of the {@link org.apache.tomcat.util.http.fileupload.FileItem FileItem} interface.

After retrieving an instance of this class from a {@link org.apache.tomcat.util.http.fileupload.DiskFileUpload DiskFileUpload} instance (see {@link org.apache.tomcat.util.http.fileupload.DiskFileUpload #parseRequest(javax.servlet.http.HttpServletRequest)}), you may either request all contents of file at once using {@link #get()} or request an {@link java.io.InputStream InputStream} with {@link #getInputStream()} and process the file without attempting to load it into memory, which may come handy with large files.

author
Rafal Krzewski
author
Sean Legassick
author
Jason van Zyl
author
John McNally
author
Martin Cooper
author
Sean C. Sullivan
version
$Id: DefaultFileItem.java 467222 2006-10-24 03:17:11Z markt $

Fields Summary
private static int
counter
Counter used in unique identifier generation.
private String
fieldName
The name of the form field as provided by the browser.
private String
contentType
The content type passed by the browser, or null if not defined.
private boolean
isFormField
Whether or not this item is a simple form field.
private String
fileName
The original filename in the user's filesystem.
private int
sizeThreshold
The threshold above which uploads will be stored on disk.
private File
repository
The directory in which uploaded files will be stored, if stored on disk.
private byte[]
cachedContent
Cached contents of the file.
private DeferredFileOutputStream
dfos
Output stream for this item.
Constructors Summary
DefaultFileItem(String fieldName, String contentType, boolean isFormField, String fileName, int sizeThreshold, File repository)
Constructs a new DefaultFileItem instance.

param
fieldName The name of the form field.
param
contentType The content type passed by the browser or null if not specified.
param
isFormField Whether or not this item is a plain form field, as opposed to a file upload.
param
fileName The original filename in the user's filesystem, or null if not specified.
param
sizeThreshold The threshold, in bytes, below which items will be retained in memory and above which they will be stored as a file.
param
repository The data repository, which is the directory in which files will be created, should the item size exceed the threshold.



    // ----------------------------------------------------------- Constructors


                                                                                                                                                                                                                                                                                     
         
                         
    
        this.fieldName = fieldName;
        this.contentType = contentType;
        this.isFormField = isFormField;
        this.fileName = fileName;
        this.sizeThreshold = sizeThreshold;
        this.repository = repository;
    
Methods Summary
public voiddelete()
Deletes the underlying storage for a file item, including deleting any associated temporary disk file. Although this storage will be deleted automatically when the FileItem instance is garbage collected, this method can be used to ensure that this is done at an earlier time, thus preserving system resources.

        cachedContent = null;
        File outputFile = getStoreLocation();
        if (outputFile != null && outputFile.exists())
        {
            outputFile.delete();
        }
    
protected voidfinalize()
Removes the file contents from the temporary storage.

        File outputFile = dfos.getFile();

        if (outputFile != null && outputFile.exists())
        {
            outputFile.delete();
        }
    
public byte[]get()
Returns the contents of the file as an array of bytes. If the contents of the file were not yet cached in memory, they will be loaded from the disk storage and cached.

return
The contents of the file as an array of bytes.

        if (dfos.isInMemory())
        {
            if (cachedContent == null)
            {
                cachedContent = dfos.getData();
            }
            return cachedContent;
        }

        byte[] fileData = new byte[(int) getSize()];
        FileInputStream fis = null;

        try
        {
            fis = new FileInputStream(dfos.getFile());
            fis.read(fileData);
        }
        catch (IOException e)
        {
            fileData = null;
        }
        finally
        {
            if (fis != null)
            {
                try
                {
                    fis.close();
                }
                catch (IOException e)
                {
                    // ignore
                }
            }
        }

        return fileData;
    
public java.lang.StringgetContentType()
Returns the content type passed by the browser or null if not defined.

return
The content type passed by the browser or null if not defined.

        return contentType;
    
public java.lang.StringgetFieldName()
Returns the name of the field in the multipart form corresponding to this file item.

return
The name of the form field.
see
#setFieldName(java.lang.String)

        return fieldName;
    
public java.io.InputStreamgetInputStream()
Returns an {@link java.io.InputStream InputStream} that can be used to retrieve the contents of the file.

return
An {@link java.io.InputStream InputStream} that can be used to retrieve the contents of the file.
exception
IOException if an error occurs.

        if (!dfos.isInMemory())
        {
            return new FileInputStream(dfos.getFile());
        }

        if (cachedContent == null)
        {
            cachedContent = dfos.getData();
        }
        return new ByteArrayInputStream(cachedContent);
    
public java.lang.StringgetName()
Returns the original filename in the client's filesystem.

return
The original filename in the client's filesystem.

        return fileName;
    
public java.io.OutputStreamgetOutputStream()
Returns an {@link java.io.OutputStream OutputStream} that can be used for storing the contents of the file.

return
An {@link java.io.OutputStream OutputStream} that can be used for storing the contensts of the file.
exception
IOException if an error occurs.

        if (dfos == null)
        {
            File outputFile = getTempFile();
            dfos = new DeferredFileOutputStream(sizeThreshold, outputFile);
        }
        return dfos;
    
public longgetSize()
Returns the size of the file.

return
The size of the file, in bytes.

        if (cachedContent != null)
        {
            return cachedContent.length;
        }
        else if (dfos.isInMemory())
        {
            return dfos.getData().length;
        }
        else
        {
            return dfos.getFile().length();
        }
    
public java.io.FilegetStoreLocation()
Returns the {@link java.io.File} object for the FileItem's data's temporary location on the disk. Note that for FileItems that have their data stored in memory, this method will return null. When handling large files, you can use {@link java.io.File#renameTo(java.io.File)} to move the file to new location without copying the data, if the source and destination locations reside within the same logical volume.

return
The data file, or null if the data is stored in memory.

        return dfos.getFile();
    
public java.lang.StringgetString(java.lang.String encoding)
Returns the contents of the file as a String, using the specified encoding. This method uses {@link #get()} to retrieve the contents of the file.

param
encoding The character encoding to use.
return
The contents of the file, as a string.
exception
UnsupportedEncodingException if the requested character encoding is not available.

        return new String(get(), encoding);
    
public java.lang.StringgetString()
Returns the contents of the file as a String, using the default character encoding. This method uses {@link #get()} to retrieve the contents of the file.

return
The contents of the file, as a string.

        return new String(get());
    
protected java.io.FilegetTempFile()
Creates and returns a {@link java.io.File File} representing a uniquely named temporary file in the configured repository path.

return
The {@link java.io.File File} to be used for temporary storage.

        File tempDir = repository;
        if (tempDir == null)
        {
            tempDir = new File(System.getProperty("java.io.tmpdir"));
        }

        String fileName = "upload_" + getUniqueId() + ".tmp";

        File f = new File(tempDir, fileName);
        f.deleteOnExit();
        return f;
    
private static java.lang.StringgetUniqueId()
Returns an identifier that is unique within the class loader used to load this class, but does not have random-like apearance.

return
A String with the non-random looking instance identifier.

        int current;
        synchronized (DefaultFileItem.class)
        {
            current = counter++;
        }
        String id = Integer.toString(current);

        // If you manage to get more than 100 million of ids, you'll
        // start getting ids longer than 8 characters.
        if (current < 100000000)
        {
            id = ("00000000" + id).substring(id.length());
        }
        return id;
    
public booleanisFormField()
Determines whether or not a FileItem instance represents a simple form field.

return
true if the instance represents a simple form field; false if it represents an uploaded file.
see
#setFormField(boolean)

        return isFormField;
    
public booleanisInMemory()
Provides a hint as to whether or not the file contents will be read from memory.

return
true if the file contents will be read from memory; false otherwise.

        return (dfos.isInMemory());
    
public voidsetFieldName(java.lang.String fieldName)
Sets the field name used to reference this file item.

param
fieldName The name of the form field.
see
#getFieldName()

        this.fieldName = fieldName;
    
public voidsetFormField(boolean state)
Specifies whether or not a FileItem instance represents a simple form field.

param
state true if the instance represents a simple form field; false if it represents an uploaded file.
see
#isFormField()

        isFormField = state;
    
public voidwrite(java.io.File file)
A convenience method to write an uploaded item to disk. The client code is not concerned with whether or not the item is stored in memory, or on disk in a temporary location. They just want to write the uploaded item to a file.

This implementation first attempts to rename the uploaded item to the specified destination file, if the item was originally written to disk. Otherwise, the data will be copied to the specified file.

This method is only guaranteed to work once, the first time it is invoked for a particular item. This is because, in the event that the method renames a temporary file, that file will no longer be available to copy or rename again at a later time.

param
file The File into which the uploaded item should be stored.
exception
Exception if an error occurs.

        if (isInMemory())
        {
            FileOutputStream fout = null;
            try
            {
                fout = new FileOutputStream(file);
                fout.write(get());
            }
            finally
            {
                if (fout != null)
                {
                    fout.close();
                }
            }
        }
        else
        {
            File outputFile = getStoreLocation();
            if (outputFile != null)
            {
                /*
                 * The uploaded file is being stored on disk
                 * in a temporary location so move it to the
                 * desired file.
                 */
                if (!outputFile.renameTo(file))
                {
                    BufferedInputStream in = null;
                    BufferedOutputStream out = null;
                    try
                    {
                        in = new BufferedInputStream(
                            new FileInputStream(outputFile));
                        out = new BufferedOutputStream(
                                new FileOutputStream(file));
                        byte[] bytes = new byte[2048];
                        int s = 0;
                        while ((s = in.read(bytes)) != -1)
                        {
                            out.write(bytes, 0, s);
                        }
                    }
                    finally
                    {
                        try
                        {
                            in.close();
                        }
                        catch (IOException e)
                        {
                            // ignore
                        }
                        try
                        {
                            out.close();
                        }
                        catch (IOException e)
                        {
                            // ignore
                        }
                    }
                }
            }
            else
            {
                /*
                 * For whatever reason we cannot write the
                 * file to disk.
                 */
                throw new FileUploadException(
                    "Cannot write uploaded file to disk!");
            }
        }