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.commons.fileupload;
  
  import static java.lang.String.format;
  
  import java.util.HashMap;
  import java.util.List;
  import java.util.Locale;
  import java.util.Map;
  
  import  javax.servlet.http.HttpServletRequest;
  

High level API for processing file uploads.

This class handles multiple files per single HTML widget, sent using multipart/mixed encoding type, as specified by RFC 1867. Use .parseRequest(RequestContext) to acquire a list of org.apache.commons.fileupload.FileItems associated with a given HTML widget.

How the data for individual parts is stored is determined by the factory used to create them; a given part may be in memory, on disk, or somewhere else.

Version:
$Id: FileUploadBase.java 1565194 2014-02-06 12:16:30Z markt $
  
  public abstract class FileUploadBase {
  
      // ---------------------------------------------------------- Class methods
  
    

Utility method that determines whether the request contains multipart content.

NOTE:This method will be moved to the ServletFileUpload class after the FileUpload 1.1 release. Unfortunately, since this method is static, it is not possible to provide its replacement until this method is removed.

Parameters:
ctx The request context to be evaluated. Must be non-null.
Returns:
true if the request is multipart; false otherwise.
  
      public static final boolean isMultipartContent(RequestContext ctx) {
          String contentType = ctx.getContentType();
          if (contentType == null) {
              return false;
          }
          if (contentType.toLowerCase(.).startsWith()) {
              return true;
          }
          return false;
      }

    
Utility method that determines whether the request contains multipart content.

Deprecated:
1.1 Use the method on ServletFileUpload instead.
Parameters:
req The servlet request to be evaluated. Must be non-null.
Returns:
true if the request is multipart; false otherwise.
  
      @Deprecated
      public static boolean isMultipartContent(HttpServletRequest req) {
         return ServletFileUpload.isMultipartContent(req);
     }
 
     // ----------------------------------------------------- Manifest constants
 
    
HTTP content type header name.
 
     public static final String CONTENT_TYPE = "Content-type";

    
HTTP content disposition header name.
 
     public static final String CONTENT_DISPOSITION = "Content-disposition";

    
HTTP content length header name.
 
     public static final String CONTENT_LENGTH = "Content-length";

    
Content-disposition value for form data.
 
     public static final String FORM_DATA = "form-data";

    
Content-disposition value for file attachment.
 
     public static final String ATTACHMENT = "attachment";

    
Part of HTTP content type header.
 
     public static final String MULTIPART = "multipart/";

    
HTTP content type header for multipart forms.
 
     public static final String MULTIPART_FORM_DATA = "multipart/form-data";

    
HTTP content type header for multiple uploads.
 
     public static final String MULTIPART_MIXED = "multipart/mixed";

    
The maximum length of a single header line that will be parsed (1024 bytes).

Deprecated:
This constant is no longer used. As of commons-fileupload 1.2, the only applicable limit is the total size of a parts headers, MultipartStream.HEADER_PART_SIZE_MAX.
 
     @Deprecated
     public static final int MAX_HEADER_SIZE = 1024;
 
     // ----------------------------------------------------------- Data members
 
    
The maximum size permitted for the complete request, as opposed to fileSizeMax. A value of -1 indicates no maximum.
 
     private long sizeMax = -1;

    
The maximum size permitted for a single uploaded file, as opposed to sizeMax. A value of -1 indicates no maximum.
 
     private long fileSizeMax = -1;

    
The content encoding to use when reading part headers.
 
     private String headerEncoding;

    
The progress listener.
 
     private ProgressListener listener;
 
     // ----------------------------------------------------- Property accessors
 
    
Returns the factory class used when creating file items.

Returns:
The factory class for new file items.
 
     public abstract FileItemFactory getFileItemFactory();

    
Sets the factory class to use when creating file items.

Parameters:
factory The factory class for new file items.
 
     public abstract void setFileItemFactory(FileItemFactory factory);

    
Returns the maximum allowed size of a complete request, as opposed to getFileSizeMax().

Returns:
The maximum allowed size, in bytes. The default value of -1 indicates, that there is no limit.
See also:
setSizeMax(long)
 
     public long getSizeMax() {
         return ;
     }

    
Sets the maximum allowed size of a complete request, as opposed to setFileSizeMax(long).

Parameters:
sizeMax The maximum allowed size, in bytes. The default value of -1 indicates, that there is no limit.
See also:
getSizeMax()
 
     public void setSizeMax(long sizeMax) {
         this. = sizeMax;
     }

    
Returns the maximum allowed size of a single uploaded file, as opposed to getSizeMax().

Returns:
Maximum size of a single uploaded file.
See also:
setFileSizeMax(long)
 
     public long getFileSizeMax() {
         return ;
     }

    
Sets the maximum allowed size of a single uploaded file, as opposed to getSizeMax().

Parameters:
fileSizeMax Maximum size of a single uploaded file.
See also:
getFileSizeMax()
 
     public void setFileSizeMax(long fileSizeMax) {
         this. = fileSizeMax;
     }

    
Retrieves the character encoding used when reading the headers of an individual part. When not specified, or null, the request encoding is used. If that is also not specified, or null, the platform default encoding is used.

Returns:
The encoding used to read part headers.
 
     public String getHeaderEncoding() {
         return ;
     }

    
Specifies the character encoding to be used when reading the headers of individual part. When not specified, or null, the request encoding is used. If that is also not specified, or null, the platform default encoding is used.

Parameters:
encoding The encoding used to read part headers.
 
     public void setHeaderEncoding(String encoding) {
          = encoding;
     }
 
     // --------------------------------------------------------- Public methods
 
    
Processes an RFC 1867 compliant multipart/form-data stream.

Deprecated:
1.1 Use ServletFileUpload.parseRequest(HttpServletRequest) instead.
Parameters:
req The servlet request to be parsed.
Returns:
A list of FileItem instances parsed from the request, in the order that they were transmitted.
Throws:
FileUploadException if there are problems reading/parsing the request or storing files.
 
     @Deprecated
     public List<FileItemparseRequest(HttpServletRequest req)
     throws FileUploadException {
         return parseRequest(new ServletRequestContext(req));
     }

    
Processes an RFC 1867 compliant multipart/form-data stream.

Parameters:
ctx The context for the request to be parsed.
Returns:
An iterator to instances of FileItemStream parsed from the request, in the order that they were transmitted.
Throws:
FileUploadException if there are problems reading/parsing the request or storing files.
IOException An I/O error occurred. This may be a network error while communicating with the client or a problem while storing the uploaded content.
 
     throws FileUploadExceptionIOException {
         try {
             return new FileItemIteratorImpl(ctx);
         } catch (FileUploadIOException e) {
             // unwrap encapsulated SizeException
             throw (FileUploadExceptione.getCause();
         }
     }

    
Processes an RFC 1867 compliant multipart/form-data stream.

Parameters:
ctx The context for the request to be parsed.
Returns:
A list of FileItem instances parsed from the request, in the order that they were transmitted.
Throws:
FileUploadException if there are problems reading/parsing the request or storing files.
 
     public List<FileItemparseRequest(RequestContext ctx)
             throws FileUploadException {
         List<FileItemitems = new ArrayList<FileItem>();
         boolean successful = false;
         try {
             FileItemIterator iter = getItemIterator(ctx);
             FileItemFactory fac = getFileItemFactory();
             if (fac == null) {
                 throw new NullPointerException("No FileItemFactory has been set.");
             }
             while (iter.hasNext()) {
                 final FileItemStream item = iter.next();
                 // Don't use getName() here to prevent an InvalidFileNameException.
                 final String fileName = ((FileItemIteratorImpl.FileItemStreamImplitem).;
                 FileItem fileItem = fac.createItem(item.getFieldName(), item.getContentType(),
                                                    item.isFormField(), fileName);
                 items.add(fileItem);
                 try {
                     Streams.copy(item.openStream(), fileItem.getOutputStream(), true);
                 } catch (FileUploadIOException e) {
                     throw (FileUploadExceptione.getCause();
                 } catch (IOException e) {
                     throw new IOFileUploadException(format("Processing of %s request failed. %s",
                                                            e.getMessage()), e);
                 }
                 final FileItemHeaders fih = item.getHeaders();
                 fileItem.setHeaders(fih);
             }
             successful = true;
             return items;
         } catch (FileUploadIOException e) {
             throw (FileUploadExceptione.getCause();
         } catch (IOException e) {
             throw new FileUploadException(e.getMessage(), e);
         } finally {
             if (!successful) {
                 for (FileItem fileItem : items) {
                     try {
                         fileItem.delete();
                     } catch (Throwable e) {
                         // ignore it
                     }
                 }
             }
         }
     }

    
Processes an RFC 1867 compliant multipart/form-data stream.

Parameters:
ctx The context for the request to be parsed.
Returns:
A map of FileItem instances parsed from the request.
Throws:
FileUploadException if there are problems reading/parsing the request or storing files.
Since:
1.3
 
             throws FileUploadException {
         final List<FileItemitems = parseRequest(ctx);
         final Map<StringList<FileItem>> itemsMap = new HashMap<StringList<FileItem>>(items.size());
 
         for (FileItem fileItem : items) {
             String fieldName = fileItem.getFieldName();
             List<FileItemmappedItems = itemsMap.get(fieldName);
 
             if (mappedItems == null) {
                 mappedItems = new ArrayList<FileItem>();
                 itemsMap.put(fieldNamemappedItems);
             }
 
             mappedItems.add(fileItem);
         }
 
         return itemsMap;
     }
 
     // ------------------------------------------------------ Protected methods
 
    
Retrieves the boundary from the Content-type header.

Parameters:
contentType The value of the content type header from which to extract the boundary value.
Returns:
The boundary, as a byte array.
 
     protected byte[] getBoundary(String contentType) {
         ParameterParser parser = new ParameterParser();
         parser.setLowerCaseNames(true);
         // Parameter parser can handle null input
         Map<StringStringparams = parser.parse(contentTypenew char[] {';'','});
         String boundaryStr = params.get("boundary");
 
         if (boundaryStr == null) {
             return null;
         }
         byte[] boundary;
         try {
             boundary = boundaryStr.getBytes("ISO-8859-1");
         } catch (UnsupportedEncodingException e) {
             boundary = boundaryStr.getBytes(); // Intentionally falls back to default charset
         }
         return boundary;
     }

    
Retrieves the file name from the Content-disposition header.

Deprecated:
1.2.1 Use getFileName(FileItemHeaders).
Parameters:
headers A Map containing the HTTP request headers.
Returns:
The file name for the current encapsulation.
 
     @Deprecated
     protected String getFileName(Map<StringStringheaders) {
         return getFileName(getHeader(headers));
     }

    
Retrieves the file name from the Content-disposition header.

Parameters:
headers The HTTP headers object.
Returns:
The file name for the current encapsulation.
 
     protected String getFileName(FileItemHeaders headers) {
         return getFileName(headers.getHeader());
     }

    
Returns the given content-disposition headers file name.

Parameters:
pContentDisposition The content-disposition headers value.
Returns:
The file name
 
     private String getFileName(String pContentDisposition) {
         String fileName = null;
         if (pContentDisposition != null) {
             String cdl = pContentDisposition.toLowerCase(.);
             if (cdl.startsWith() || cdl.startsWith()) {
                 ParameterParser parser = new ParameterParser();
                 parser.setLowerCaseNames(true);
                 // Parameter parser can handle null input
                 Map<StringStringparams = parser.parse(pContentDisposition';');
                 if (params.containsKey("filename")) {
                     fileName = params.get("filename");
                     if (fileName != null) {
                         fileName = fileName.trim();
                     } else {
                         // Even if there is no value, the parameter is present,
                         // so we return an empty file name rather than no file
                         // name.
                         fileName = "";
                     }
                 }
             }
         }
         return fileName;
     }

    
Retrieves the field name from the Content-disposition header.

Parameters:
headers A Map containing the HTTP request headers.
Returns:
The field name for the current encapsulation.
 
     protected String getFieldName(FileItemHeaders headers) {
         return getFieldName(headers.getHeader());
     }

    
Returns the field name, which is given by the content-disposition header.

Parameters:
pContentDisposition The content-dispositions header value.
Returns:
The field jake
 
     private String getFieldName(String pContentDisposition) {
         String fieldName = null;
         if (pContentDisposition != null
                 && pContentDisposition.toLowerCase(.).startsWith()) {
             ParameterParser parser = new ParameterParser();
             parser.setLowerCaseNames(true);
             // Parameter parser can handle null input
             Map<StringStringparams = parser.parse(pContentDisposition';');
             fieldName = params.get("name");
             if (fieldName != null) {
                 fieldName = fieldName.trim();
             }
         }
         return fieldName;
     }

    
Retrieves the field name from the Content-disposition header.

Deprecated:
1.2.1 Use getFieldName(FileItemHeaders).
Parameters:
headers A Map containing the HTTP request headers.
Returns:
The field name for the current encapsulation.
 
     @Deprecated
     protected String getFieldName(Map<StringStringheaders) {
         return getFieldName(getHeader(headers));
     }

    
Creates a new FileItem instance.

Deprecated:
1.2 This method is no longer used in favour of internally created instances of FileItem.
Parameters:
headers A Map containing the HTTP request headers.
isFormField Whether or not this item is a form field, as opposed to a file.
Returns:
A newly created FileItem instance.
Throws:
FileUploadException if an error occurs.
 
     @Deprecated
     protected FileItem createItem(Map<StringStringheaders,
                                   boolean isFormField)
         throws FileUploadException {
         return getFileItemFactory().createItem(getFieldName(headers),
                 getHeader(headers),
                 isFormField,
                 getFileName(headers));
     }

    

Parses the header-part and returns as key/value pairs.

If there are multiple headers of the same names, the name will map to a comma-separated list containing the values.

Parameters:
headerPart The header-part of the current encapsulation.
Returns:
A Map containing the parsed HTTP request headers.
 
     protected FileItemHeaders getParsedHeaders(String headerPart) {
         final int len = headerPart.length();
         FileItemHeadersImpl headers = newFileItemHeaders();
         int start = 0;
         for (;;) {
             int end = parseEndOfLine(headerPartstart);
             if (start == end) {
                 break;
             }
             StringBuilder header = new StringBuilder(headerPart.substring(startend));
             start = end + 2;
             while (start < len) {
                 int nonWs = start;
                 while (nonWs < len) {
                     char c = headerPart.charAt(nonWs);
                     if (c != ' '  &&  c != '\t') {
                         break;
                     }
                     ++nonWs;
                 }
                 if (nonWs == start) {
                     break;
                 }
                 // Continuation line found
                 end = parseEndOfLine(headerPartnonWs);
                 header.append(" ").append(headerPart.substring(nonWsend));
                 start = end + 2;
             }
             parseHeaderLine(headersheader.toString());
         }
         return headers;
     }

    
Creates a new instance of FileItemHeaders.

Returns:
The new instance.
 
     protected FileItemHeadersImpl newFileItemHeaders() {
         return new FileItemHeadersImpl();
     }

    

Parses the header-part and returns as key/value pairs.

If there are multiple headers of the same names, the name will map to a comma-separated list containing the values.

Deprecated:
1.2.1 Use getParsedHeaders(String)
Parameters:
headerPart The header-part of the current encapsulation.
Returns:
A Map containing the parsed HTTP request headers.
 
     @Deprecated
     protected Map<StringStringparseHeaders(String headerPart) {
         FileItemHeaders headers = getParsedHeaders(headerPart);
         Map<StringStringresult = new HashMap<StringString>();
         for (Iterator<Stringiter = headers.getHeaderNames();  iter.hasNext();) {
             String headerName = iter.next();
             Iterator<Stringiter2 = headers.getHeaders(headerName);
             StringBuilder headerValue = new StringBuilder(iter2.next());
             while (iter2.hasNext()) {
                 headerValue.append(",").append(iter2.next());
             }
             result.put(headerNameheaderValue.toString());
         }
         return result;
     }

    
Skips bytes until the end of the current line.

Parameters:
headerPart The headers, which are being parsed.
end Index of the last byte, which has yet been processed.
Returns:
Index of the \r\n sequence, which indicates end of line.
 
     private int parseEndOfLine(String headerPartint end) {
         int index = end;
         for (;;) {
             int offset = headerPart.indexOf('\r'index);
             if (offset == -1  ||  offset + 1 >= headerPart.length()) {
                 throw new IllegalStateException(
                     "Expected headers to be terminated by an empty line.");
             }
             if (headerPart.charAt(offset + 1) == '\n') {
                 return offset;
             }
             index = offset + 1;
         }
     }

    
Reads the next header line.

Parameters:
headers String with all headers.
header Map where to store the current header.
 
     private void parseHeaderLine(FileItemHeadersImpl headersString header) {
         final int colonOffset = header.indexOf(':');
         if (colonOffset == -1) {
             // This header line is malformed, skip it.
             return;
         }
         String headerName = header.substring(0, colonOffset).trim();
         String headerValue =
             header.substring(header.indexOf(':') + 1).trim();
         headers.addHeader(headerNameheaderValue);
     }

    
Returns the header with the specified name from the supplied map. The header lookup is case-insensitive.

Deprecated:
1.2.1 Use FileItemHeaders.getHeader(String).
Parameters:
headers A Map containing the HTTP request headers.
name The name of the header to return.
Returns:
The value of specified header, or a comma-separated list if there were multiple headers of that name.
 
     @Deprecated
     protected final String getHeader(Map<StringStringheaders,
             String name) {
         return headers.get(name.toLowerCase(.));
     }

    
The iterator, which is returned by FileUploadBase.getItemIterator(RequestContext).
 
     private class FileItemIteratorImpl implements FileItemIterator {

        
Default implementation of FileItemStream.
 
         class FileItemStreamImpl implements FileItemStream {

            
The file items content type.
 
             private final String contentType;

            
The file items field name.
 
             private final String fieldName;

            
The file items file name.
 
             private final String name;

            
Whether the file item is a form field.
 
             private final boolean formField;

            
The file items input stream.
 
             private final InputStream stream;

            
Whether the file item was already opened.
 
             private boolean opened;

            
The headers, if any.
 
             private FileItemHeaders headers;

            
Creates a new instance.

Parameters:
pName The items file name, or null.
pFieldName The items field name.
pContentType The items content type, or null.
pFormField Whether the item is a form field.
pContentLength The items content length, if known, or -1
Throws:
IOException Creating the file item failed.
 
             FileItemStreamImpl(String pNameString pFieldName,
                     String pContentTypeboolean pFormField,
                     long pContentLengththrows IOException {
                  = pName;
                  = pFieldName;
                  = pContentType;
                  = pFormField;
                 final ItemInputStream itemStream = .newInputStream();
                 InputStream istream = itemStream;
                 if ( != -1) {
                     if (pContentLength != -1
                             &&  pContentLength > ) {
                         FileSizeLimitExceededException e =
                             new FileSizeLimitExceededException(
                                 format("The field %s exceeds its maximum permitted size of %s bytes.",
                                        , Long.valueOf()),
                                 pContentLength);
                         e.setFileName(pName);
                         e.setFieldName(pFieldName);
                         throw new FileUploadIOException(e);
                     }
                     istream = new LimitedInputStream(istream) {
                         @Override
                         protected void raiseError(long pSizeMaxlong pCount)
                                 throws IOException {
                             itemStream.close(true);
                             FileSizeLimitExceededException e =
                                 new FileSizeLimitExceededException(
                                     format("The field %s exceeds its maximum permitted size of %s bytes.",
                                            , Long.valueOf(pSizeMax)),
                                     pCountpSizeMax);
                             e.setFieldName();
                             e.setFileName();
                             throw new FileUploadIOException(e);
                         }
                     };
                 }
                  = istream;
             }

            
Returns the items content type, or null.

Returns:
Content type, if known, or null.
 
             public String getContentType() {
                 return ;
             }

            
Returns the items field name.

Returns:
Field name.
 
             public String getFieldName() {
                 return ;
             }

            
Returns the items file name.

Returns:
File name, if known, or null.
Throws:
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();
             }

            
Returns, whether this is a form field.

Returns:
True, if the item is a form field, otherwise false.
 
             public boolean isFormField() {
                 return ;
             }

            
Returns an input stream, which may be used to read the items contents.

Returns:
Opened input stream.
Throws:
IOException An I/O error occurred.
 
             public InputStream openStream() throws IOException {
                 if () {
                     throw new IllegalStateException(
                             "The stream was already opened.");
                 }
                 if (((Closeable).isClosed()) {
                     throw new FileItemStream.ItemSkippedException();
                 }
                 return ;
             }

            
Closes the file item.

Throws:
IOException An I/O error occurred.
 
             void close() throws IOException {
                 .close();
             }

            
Returns the file item headers.

Returns:
The items header object
 
             public FileItemHeaders getHeaders() {
                 return ;
             }

            
Sets the file item headers.

Parameters:
pHeaders The items header object
 
             public void setHeaders(FileItemHeaders pHeaders) {
                  = pHeaders;
             }
 
         }

        
The multi part stream to process.
 
         private final MultipartStream multi;

        
The notifier, which used for triggering the ProgressListener.
 
         private final MultipartStream.ProgressNotifier notifier;

        
The boundary, which separates the various parts.
 
         private final byte[] boundary;

        
The item, which we currently process.
 
         private FileItemStreamImpl currentItem;

        
The current items field name.
 
         private String currentFieldName;

        
Whether we are currently skipping the preamble.
 
         private boolean skipPreamble;

        
Whether the current item may still be read.
 
         private boolean itemValid;

        
Whether we have seen the end of the file.
 
         private boolean eof;

        
Creates a new instance.

Parameters:
ctx The request context.
Throws:
FileUploadException An error occurred while parsing the request.
IOException An I/O error occurred.
 
         FileItemIteratorImpl(RequestContext ctx)
                 throws FileUploadExceptionIOException {
             if (ctx == null) {
                 throw new NullPointerException("ctx parameter");
             }
 
             String contentType = ctx.getContentType();
             if ((null == contentType)
                     || (!contentType.toLowerCase(.).startsWith())) {
                 throw new InvalidContentTypeException(
                         format("the request doesn't contain a %s or %s stream, content type header is %s",
                                contentType));
             }
 
             InputStream input = ctx.getInputStream();
 
             @SuppressWarnings("deprecation"// still has to be backward compatible
             final int contentLengthInt = ctx.getContentLength();
 
             final long requestSize = UploadContext.class.isAssignableFrom(ctx.getClass())
                                      // Inline conditional is OK here CHECKSTYLE:OFF
                                      ? ((UploadContextctx).contentLength()
                                      : contentLengthInt;
                                      // CHECKSTYLE:ON
 
             if ( >= 0) {
                 if (requestSize != -1 && requestSize > ) {
                     throw new SizeLimitExceededException(
                         format("the request was rejected because its size (%s) exceeds the configured maximum (%s)",
                                 Long.valueOf(requestSize), Long.valueOf()),
                                requestSize);
                 }
                 input = new LimitedInputStream(input) {
                     @Override
                     protected void raiseError(long pSizeMaxlong pCount)
                             throws IOException {
                         FileUploadException ex = new SizeLimitExceededException(
                         format("the request was rejected because its size (%s) exceeds the configured maximum (%s)",
                                 Long.valueOf(pCount), Long.valueOf(pSizeMax)),
                                pCountpSizeMax);
                         throw new FileUploadIOException(ex);
                     }
                 };
             }
 
             String charEncoding = ;
             if (charEncoding == null) {
                 charEncoding = ctx.getCharacterEncoding();
             }
 
              = getBoundary(contentType);
             if ( == null) {
                 throw new FileUploadException("the request was rejected because no multipart boundary was found");
             }
 
              = new MultipartStream.ProgressNotifier(requestSize);
             try {
                  = new MultipartStream(input);
             } catch (IllegalArgumentException iae) {
                 throw new InvalidContentTypeException(
                         format("The boundary specified in the %s header is too long"), iae);
             }
            .setHeaderEncoding(charEncoding);
             = true;
            findNextItem();
        }

        
Called for finding the next item, if any.

Returns:
True, if an next item was found, otherwise false.
Throws:
IOException An I/O error occurred.
        private boolean findNextItem() throws IOException {
            if () {
                return false;
            }
            if ( != null) {
                .close();
                 = null;
            }
            for (;;) {
                boolean nextPart;
                if () {
                    nextPart = .skipPreamble();
                } else {
                    nextPart = .readBoundary();
                }
                if (!nextPart) {
                    if ( == null) {
                        // Outer multipart terminated -> No more data
                         = true;
                        return false;
                    }
                    // Inner multipart terminated -> Return to parsing the outer
                    .setBoundary();
                     = null;
                    continue;
                }
                FileItemHeaders headers = getParsedHeaders(.readHeaders());
                if ( == null) {
                    // We're parsing the outer multipart
                    String fieldName = getFieldName(headers);
                    if (fieldName != null) {
                        String subContentType = headers.getHeader();
                        if (subContentType != null
                                &&  subContentType.toLowerCase(.)
                                        .startsWith()) {
                             = fieldName;
                            // Multiple files associated with this field name
                            byte[] subBoundary = getBoundary(subContentType);
                            .setBoundary(subBoundary);
                             = true;
                            continue;
                        }
                        String fileName = getFileName(headers);
                         = new FileItemStreamImpl(fileName,
                                fieldNameheaders.getHeader(),
                                fileName == nullgetContentLength(headers));
                        .setHeaders(headers);
                        .noteItem();
                         = true;
                        return true;
                    }
                } else {
                    String fileName = getFileName(headers);
                    if (fileName != null) {
                         = new FileItemStreamImpl(fileName,
                                ,
                                headers.getHeader(),
                                falsegetContentLength(headers));
                        .setHeaders(headers);
                        .noteItem();
                         = true;
                        return true;
                    }
                }
                .discardBodyData();
            }
        }
        private long getContentLength(FileItemHeaders pHeaders) {
            try {
                return Long.parseLong(pHeaders.getHeader());
            } catch (Exception e) {
                return -1;
            }
        }

        
Returns, whether another instance of FileItemStream is available.

Returns:
True, if one or more additional file items are available, otherwise false.
Throws:
FileUploadException Parsing or processing the file item failed.
IOException Reading the file item failed.
        public boolean hasNext() throws FileUploadExceptionIOException {
            if () {
                return false;
            }
            if () {
                return true;
            }
            try {
                return findNextItem();
            } catch (FileUploadIOException e) {
                // unwrap encapsulated SizeException
                throw (FileUploadExceptione.getCause();
            }
        }

        
Returns the next available FileItemStream.

Returns:
FileItemStream instance, which provides access to the next file item.
Throws:
java.util.NoSuchElementException No more items are available. Use hasNext() to prevent this exception.
FileUploadException Parsing or processing the file item failed.
IOException Reading the file item failed.
        public FileItemStream next() throws FileUploadExceptionIOException {
            if (  ||  (! && !hasNext())) {
                throw new NoSuchElementException();
            }
             = false;
            return ;
        }
    }

    
This exception is thrown for hiding an inner FileUploadException in an IOException.
    public static class FileUploadIOException extends IOException {

        
The exceptions UID, for serializing an instance.
        private static final long serialVersionUID = -7047616958165584154L;

        
The exceptions cause; we overwrite the parent classes field, which is available since Java 1.4 only.
        private final FileUploadException cause;

        
Creates a FileUploadIOException with the given cause.

Parameters:
pCause The exceptions cause, if any, or null.
        public FileUploadIOException(FileUploadException pCause) {
            // We're not doing super(pCause) cause of 1.3 compatibility.
             = pCause;
        }

        
Returns the exceptions cause.

Returns:
The exceptions cause, if any, or null.
        @Override
        public Throwable getCause() {
            return ;
        }
    }

    
Thrown to indicate that the request is not a multipart request.
    public static class InvalidContentTypeException
            extends FileUploadException {

        
The exceptions UID, for serializing an instance.
        private static final long serialVersionUID = -9073026332015646668L;

        
Constructs a InvalidContentTypeException with no detail message.
        public InvalidContentTypeException() {
            super();
        }

        
Constructs an InvalidContentTypeException with the specified detail message.

Parameters:
message The detail message.
        public InvalidContentTypeException(String message) {
            super(message);
        }

        
Constructs an InvalidContentTypeException with the specified detail message and cause.

Parameters:
msg The detail message.
cause the original cause
Since:
1.3.1
        public InvalidContentTypeException(String msgThrowable cause) {
            super(msgcause);
        }
    }

    
Thrown to indicate an IOException.
    public static class IOFileUploadException extends FileUploadException {

        
The exceptions UID, for serializing an instance.
        private static final long serialVersionUID = 1749796615868477269L;

        
The exceptions cause; we overwrite the parent classes field, which is available since Java 1.4 only.
        private final IOException cause;

        
Creates a new instance with the given cause.

Parameters:
pMsg The detail message.
pException The exceptions cause.
        public IOFileUploadException(String pMsgIOException pException) {
            super(pMsg);
             = pException;
        }

        
Returns the exceptions cause.

Returns:
The exceptions cause, if any, or null.
        @Override
        public Throwable getCause() {
            return ;
        }
    }

    
This exception is thrown, if a requests permitted size is exceeded.
    protected abstract static class SizeException extends FileUploadException {

        
Serial version UID, being used, if serialized.
        private static final long serialVersionUID = -8776225574705254126L;

        
The actual size of the request.
        private final long actual;

        
The maximum permitted size of the request.
        private final long permitted;

        
Creates a new instance.

Parameters:
message The detail message.
actual The actual number of bytes in the request.
permitted The requests size limit, in bytes.
        protected SizeException(String messagelong actuallong permitted) {
            super(message);
            this. = actual;
            this. = permitted;
        }

        
Retrieves the actual size of the request.

Returns:
The actual size of the request.
Since:
1.3
        public long getActualSize() {
            return ;
        }

        
Retrieves the permitted size of the request.

Returns:
The permitted size of the request.
Since:
1.3
        public long getPermittedSize() {
            return ;
        }
    }

    
Thrown to indicate that the request size is not specified. In other words, it is thrown, if the content-length header is missing or contains the value -1.

Deprecated:
1.2 As of commons-fileupload 1.2, the presence of a content-length header is no longer required.
    public static class UnknownSizeException
        extends FileUploadException {

        
The exceptions UID, for serializing an instance.
        private static final long serialVersionUID = 7062279004812015273L;

        
Constructs a UnknownSizeException with no detail message.
        public UnknownSizeException() {
            super();
        }

        
Constructs an UnknownSizeException with the specified detail message.

Parameters:
message The detail message.
        public UnknownSizeException(String message) {
            super(message);
        }
    }

    
Thrown to indicate that the request size exceeds the configured maximum.
    public static class SizeLimitExceededException
            extends SizeException {

        
The exceptions UID, for serializing an instance.
        private static final long serialVersionUID = -2474893167098052828L;

        

Deprecated:
1.2 Replaced by SizeLimitExceededException(String, long, long)
        @Deprecated
        public SizeLimitExceededException() {
            this(null, 0, 0);
        }

        

Deprecated:
1.2 Replaced by SizeLimitExceededException(String, long, long)
Parameters:
message The exceptions detail message.
        @Deprecated
        public SizeLimitExceededException(String message) {
            this(message, 0, 0);
        }

        
Constructs a SizeExceededException with the specified detail message, and actual and permitted sizes.

Parameters:
message The detail message.
actual The actual request size.
permitted The maximum permitted request size.
        public SizeLimitExceededException(String messagelong actual,
                long permitted) {
            super(messageactualpermitted);
        }
    }

    
Thrown to indicate that A files size exceeds the configured maximum.
    public static class FileSizeLimitExceededException
            extends SizeException {

        
The exceptions UID, for serializing an instance.
        private static final long serialVersionUID = 8150776562029630058L;

        
File name of the item, which caused the exception.
        private String fileName;

        
Field name of the item, which caused the exception.
        private String fieldName;

        
Constructs a SizeExceededException with the specified detail message, and actual and permitted sizes.

Parameters:
message The detail message.
actual The actual request size.
permitted The maximum permitted request size.
        public FileSizeLimitExceededException(String messagelong actual,
                long permitted) {
            super(messageactualpermitted);
        }

        
Returns the file name of the item, which caused the exception.

Returns:
File name, if known, or null.
        public String getFileName() {
            return ;
        }

        
Sets the file name of the item, which caused the exception.

Parameters:
pFileName the file name of the item, which caused the exception.
        public void setFileName(String pFileName) {
             = pFileName;
        }

        
Returns the field name of the item, which caused the exception.

Returns:
Field name, if known, or null.
        public String getFieldName() {
            return ;
        }

        
Sets the field name of the item, which caused the exception.

Parameters:
pFieldName the field name of the item, which caused the exception.
        public void setFieldName(String pFieldName) {
             = pFieldName;
        }
    }

    
Returns the progress listener.

Returns:
The progress listener, if any, or null.
        return ;
    }

    
Sets the progress listener.

Parameters:
pListener The progress listener, if any. Defaults to null.
    public void setProgressListener(ProgressListener pListener) {
         = pListener;
    }