Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Licensed to the Apache Software Foundation (ASF) under one or more
   * contributor license agreements.  See the NOTICE file distributed with
   * this work for additional information regarding copyright ownership.
   * The ASF licenses this file to You under the Apache License, Version 2.0
   * (the "License"); you may not use this file except in compliance with
   * the License.  You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 package org.apache.tomcat.util.http.fileupload.disk;
 
 import static org.jboss.web.FileUploadMessages.MESSAGES;
 
 import java.io.File;
 import java.util.Map;
 

The default implementation of the FileItem interface.

After retrieving an instance of this class from a org.apache.tomcat.util.http.fileupload.FileUpload instance (see org.apache.tomcat.util.http.fileupload.FileUploadBase.parseRequest(org.apache.tomcat.util.http.fileupload.RequestContext)), you may either request all contents of file at once using get() or request an InputStream with getInputStream() and process the file without attempting to load it into memory, which may come handy with large files.

Temporary files, which are created for file items, should be deleted later on. The best way to do this is using a FileCleaningTracker, which you can set on the DiskFileItemFactory. However, if you do use such a tracker, then you must consider the following: Temporary files are automatically deleted as soon as they are no longer needed. (More precisely, when the corresponding instance of java.io.File is garbage collected.) This is done by the so-called reaper thread, which is started automatically when the class org.apache.commons.io.FileCleaner is loaded. It might make sense to terminate that thread, for example, if your web application ends. See the section on "Resource cleanup" in the users guide of commons-fileupload.

Author(s):
Rafal Krzewski
Sean Legassick
Jason van Zyl
John McNally
Martin Cooper
Sean C. Sullivan
Version:
$Id: DiskFileItem.java 981816 2010-08-03 10:44:58Z markt $
Since:
FileUpload 1.1
 
 public class DiskFileItem
     implements FileItemFileItemHeadersSupport {
 
     // ----------------------------------------------------- Manifest constants
 
    
Default content charset to be used when no explicit charset parameter is provided by the sender. Media subtypes of the "text" type are defined to have a default charset value of "ISO-8859-1" when received via HTTP.
 
     public static final String DEFAULT_CHARSET = "ISO-8859-1";
 
 
     // ----------------------------------------------------------- Data members
 

    
UID used in unique file name generation.
    private static final String UID =
            new java.rmi.server.UID().toString()
                .replace(':''_').replace('-''_');

    
Counter used in unique identifier generation.
    private static int counter = 0;


    
The name of the form field as provided by the browser.
    private String fieldName;


    
The content type passed by the browser, or null if not defined.
    private String contentType;


    
Whether or not this item is a simple form field.
    private boolean isFormField;


    
The original filename in the user's filesystem.
    private String fileName;


    
The size of the item, in bytes. This is used to cache the size when a file item is moved from its original location.
    private long size = -1;


    
The threshold above which uploads will be stored on disk.
    private int sizeThreshold;


    
The directory in which uploaded files will be stored, if stored on disk.
    private File repository;


    
Cached contents of the file.
    private byte[] cachedContent;


    
Output stream for this item.
    private transient DeferredFileOutputStream dfos;

    
The temporary file to use.
    private transient File tempFile;

    
The file items headers.
    private FileItemHeaders headers;
    // ----------------------------------------------------------- Constructors


    
Constructs a new DiskFileItem instance.

Parameters:
fieldName The name of the form field.
contentType The content type passed by the browser or null if not specified.
isFormField Whether or not this item is a plain form field, as opposed to a file upload.
fileName The original filename in the user's filesystem, or null if not specified.
sizeThreshold The threshold, in bytes, below which items will be retained in memory and above which they will be stored as a file.
repository The data repository, which is the directory in which files will be created, should the item size exceed the threshold.
    public DiskFileItem(String fieldName,
            String contentTypeboolean isFormFieldString fileName,
            int sizeThresholdFile repository) {
        this. = fieldName;
        this. = contentType;
        this. = isFormField;
        this. = fileName;
        this. = sizeThreshold;
        this. = repository;
    }
    // ------------------------------- Methods from javax.activation.DataSource


    
Returns an InputStream that can be used to retrieve the contents of the file.

Returns:
An InputStream that can be used to retrieve the contents of the file.
Throws:
java.io.IOException if an error occurs.
    public InputStream getInputStream()
        throws IOException {
        if (!isInMemory()) {
            return new FileInputStream(.getFile());
        }
        if ( == null) {
             = .getData();
        }
        return new ByteArrayInputStream();
    }


    
Returns the content type passed by the agent or null if not defined.

Returns:
The content type passed by the agent or null if not defined.
    public String getContentType() {
        return ;
    }


    
Returns the content charset passed by the agent or null if not defined.

Returns:
The content charset passed by the agent or null if not defined.
    public String getCharSet() {
        ParameterParser parser = new ParameterParser();
        parser.setLowerCaseNames(true);
        // Parameter parser can handle null input
        Map<String,Stringparams = parser.parse(getContentType(), ';');
        return params.get("charset");
    }


    
Returns the original filename in the client's filesystem.

Returns:
The original filename in the client's filesystem.
Throws:
org.apache.tomcat.util.http.fileupload.InvalidFileNameException The file name contains a NUL character, which might be an indicator of a security attack. If you intend to use the file name anyways, catch the exception and use InvalidFileNameException#getName().
    public String getName() {
        return Streams.checkFileName();
    }
    // ------------------------------------------------------- FileItem methods


    
Provides a hint as to whether or not the file contents will be read from memory.

Returns:
true if the file contents will be read from memory; false otherwise.
    public boolean isInMemory() {
        if ( != null) {
            return true;
        }
        return .isInMemory();
    }


    
Returns the size of the file.

Returns:
The size of the file, in bytes.
    public long getSize() {
        if ( >= 0) {
            return ;
        } else if ( != null) {
            return .;
        } else if (.isInMemory()) {
            return .getData().length;
        } else {
            return .getFile().length();
        }
    }


    
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.

Returns:
The contents of the file as an array of bytes.
    public byte[] get() {
        if (isInMemory()) {
            if ( == null) {
                 = .getData();
            }
            return ;
        }
        byte[] fileData = new byte[(intgetSize()];
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(.getFile());
            fis.read(fileData);
        } catch (IOException e) {
            fileData = null;
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    // ignore
                }
            }
        }
        return fileData;
    }


    
Returns the contents of the file as a String, using the specified encoding. This method uses get() to retrieve the contents of the file.

Parameters:
charset The charset to use.
Returns:
The contents of the file, as a string.
Throws:
java.io.UnsupportedEncodingException if the requested character encoding is not available.
    public String getString(final String charset)
        throws UnsupportedEncodingException {
        return new String(get(), charset);
    }


    
Returns the contents of the file as a String, using the default character encoding. This method uses get() to retrieve the contents of the file.

Returns:
The contents of the file, as a string. TODO Consider making this method throw UnsupportedEncodingException.
    public String getString() {
        byte[] rawdata = get();
        String charset = getCharSet();
        if (charset == null) {
            charset = ;
        }
        try {
            return new String(rawdatacharset);
        } catch (UnsupportedEncodingException e) {
            return new String(rawdata);
        }
    }


    
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.

Parameters:
file The File into which the uploaded item should be stored.
Throws:
java.lang.Exception if an error occurs.
    public void write(File filethrows Exception {
        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) {
                // Save the length of the file
                 = outputFile.length();
                /*
                 * 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));
                        IOUtils.copy(inout);
                    } finally {
                        if (in != null) {
                            try {
                                in.close();
                            } catch (IOException e) {
                                // ignore
                            }
                        }
                        if (out != null) {
                            try {
                                out.close();
                            } catch (IOException e) {
                                // ignore
                            }
                        }
                    }
                }
            } else {
                /*
                 * For whatever reason we cannot write the
                 * file to disk.
                 */
                throw new FileUploadException(.errorWritingUpload());
            }
        }
    }


    
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.
    public void delete() {
         = null;
        File outputFile = getStoreLocation();
        if (outputFile != null && outputFile.exists()) {
            outputFile.delete();
        }
    }


    
Returns the name of the field in the multipart form corresponding to this file item.

Returns:
The name of the form field.
See also:
setFieldName(java.lang.String)
    public String getFieldName() {
        return ;
    }


    
Sets the field name used to reference this file item.

Parameters:
fieldName The name of the form field.
See also:
getFieldName()
    public void setFieldName(String fieldName) {
        this. = fieldName;
    }


    
Determines whether or not a FileItem instance represents a simple form field.

Returns:
true if the instance represents a simple form field; false if it represents an uploaded file.
See also:
setFormField(boolean)
    public boolean isFormField() {
        return ;
    }


    
Specifies whether or not a FileItem instance represents a simple form field.

Parameters:
state true if the instance represents a simple form field; false if it represents an uploaded file.
See also:
isFormField()
    public void setFormField(boolean state) {
         = state;
    }


    
Returns an OutputStream that can be used for storing the contents of the file.

Returns:
An OutputStream that can be used for storing the contensts of the file.
Throws:
java.io.IOException if an error occurs.
    public OutputStream getOutputStream()
        throws IOException {
        if ( == null) {
            File outputFile = getTempFile();
             = new DeferredFileOutputStream(outputFile);
        }
        return ;
    }
    // --------------------------------------------------------- Public methods


    
Returns the 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 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.

Returns:
The data file, or null if the data is stored in memory.
    public File getStoreLocation() {
        return  == null ? null : .getFile();
    }
    // ------------------------------------------------------ Protected methods


    
Removes the file contents from the temporary storage.
    @Override
    protected void finalize() {
        File outputFile = .getFile();
        if (outputFile != null && outputFile.exists()) {
            outputFile.delete();
        }
    }


    
Creates and returns a File representing a uniquely named temporary file in the configured repository path. The lifetime of the file is tied to the lifetime of the FileItem instance; the file will be deleted when the instance is garbage collected.

Returns:
The File to be used for temporary storage.
    protected File getTempFile() {
        if ( == null) {
            File tempDir = ;
            if (tempDir == null) {
                tempDir = new File(System.getProperty("java.io.tmpdir"));
            }
            String tempFileName =
                "upload_" +  + "_" + getUniqueId() + ".tmp";
             = new File(tempDirtempFileName);
        }
        return ;
    }
    // -------------------------------------------------------- Private methods


    
Returns an identifier that is unique within the class loader used to load this class, but does not have random-like apearance.

Returns:
A String with the non-random looking instance identifier.
    private static String getUniqueId() {
        final int limit = 100000000;
        int current;
        synchronized (DiskFileItem.class) {
            current = ++;
        }
        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 < limit) {
            id = ("00000000" + id).substring(id.length());
        }
        return id;
    }




    
Returns a string representation of this object.

Returns:
a string representation of this object.
    @Override
    public String toString() {
        return "name=" + this.getName()
            + ", StoreLocation="
            + String.valueOf(this.getStoreLocation())
            + ", size="
            + this.getSize()
            + "bytes, "
            + "isFormField=" + isFormField()
            + ", FieldName="
            + this.getFieldName();
    }


    
Returns the file item headers.

Returns:
The file items headers.
    public FileItemHeaders getHeaders() {
        return ;
    }

    
Sets the file item headers.

Parameters:
pHeaders The file items headers.
    public void setHeaders(FileItemHeaders pHeaders) {
         = pHeaders;
    }
New to GrepCode? Check out our FAQ X