首页

关于apache的commons-fileupload包文件上传源码FileUploadBase类分析说明

标签:文件上传,FileUpload,apache,commons-fileupload,FileUploadBase     发布时间:2018-02-19   

一、前言

关于apachecommons-fileupload包中文件上传org.apache.commons.fileupload.FileUploadBase基类,详情参见源码说明

二、源码说明

1.FileUloadBase

package org.apache.commons.fileupload;@b@@b@import java.io.IOException;@b@import java.io.InputStream;@b@import java.io.UnsupportedEncodingException;@b@import java.util.ArrayList;@b@import java.util.HashMap;@b@import java.util.Iterator;@b@import java.util.List;@b@import java.util.Locale;@b@import java.util.Map;@b@import java.util.NoSuchElementException;@b@import javax.servlet.http.HttpServletRequest;@b@import org.apache.commons.fileupload.servlet.ServletFileUpload;@b@import org.apache.commons.fileupload.servlet.ServletRequestContext;@b@import org.apache.commons.fileupload.util.Closeable;@b@import org.apache.commons.fileupload.util.FileItemHeadersImpl;@b@import org.apache.commons.fileupload.util.LimitedInputStream;@b@import org.apache.commons.fileupload.util.Streams;@b@@b@public abstract class FileUploadBase@b@{@b@  public static final String CONTENT_TYPE = "Content-type";@b@  public static final String CONTENT_DISPOSITION = "Content-disposition";@b@  public static final String CONTENT_LENGTH = "Content-length";@b@  public static final String FORM_DATA = "form-data";@b@  public static final String ATTACHMENT = "attachment";@b@  public static final String MULTIPART = "multipart/";@b@  public static final String MULTIPART_FORM_DATA = "multipart/form-data";@b@  public static final String MULTIPART_MIXED = "multipart/mixed";@b@@b@  @Deprecated@b@  public static final int MAX_HEADER_SIZE = 1024;@b@  private long sizeMax;@b@  private long fileSizeMax;@b@  private String headerEncoding;@b@  private ProgressListener listener;@b@@b@  public FileUploadBase()@b@  {@b@    this.sizeMax = -1L;@b@@b@    this.fileSizeMax = -1L;@b@  }@b@@b@  public static final boolean isMultipartContent(RequestContext ctx)@b@  {@b@    String contentType = ctx.getContentType();@b@    if (contentType == null) {@b@      return false;@b@    }@b@@b@    return (contentType.toLowerCase(Locale.ENGLISH).startsWith("multipart/"));@b@  }@b@@b@  @Deprecated@b@  public static boolean isMultipartContent(HttpServletRequest req)@b@  {@b@    return ServletFileUpload.isMultipartContent(req);@b@  }@b@@b@  public abstract FileItemFactory getFileItemFactory();@b@@b@  public abstract void setFileItemFactory(FileItemFactory paramFileItemFactory);@b@@b@  public long getSizeMax()@b@  {@b@    return this.sizeMax;@b@  }@b@@b@  public void setSizeMax(long sizeMax)@b@  {@b@    this.sizeMax = sizeMax;@b@  }@b@@b@  public long getFileSizeMax()@b@  {@b@    return this.fileSizeMax;@b@  }@b@@b@  public void setFileSizeMax(long fileSizeMax)@b@  {@b@    this.fileSizeMax = fileSizeMax;@b@  }@b@@b@  public String getHeaderEncoding()@b@  {@b@    return this.headerEncoding;@b@  }@b@@b@  public void setHeaderEncoding(String encoding)@b@  {@b@    this.headerEncoding = encoding;@b@  }@b@@b@  @Deprecated@b@  public List<FileItem> parseRequest(HttpServletRequest req)@b@    throws FileUploadException@b@  {@b@    return parseRequest(new ServletRequestContext(req));@b@  }@b@@b@  public FileItemIterator getItemIterator(RequestContext ctx)@b@    throws FileUploadException, IOException@b@  {@b@    try@b@    {@b@      return new FileItemIteratorImpl(ctx);@b@    }@b@    catch (FileUploadIOException e) {@b@      throw ((FileUploadException)e.getCause());@b@    }@b@  }@b@@b@  public List<FileItem> parseRequest(RequestContext ctx)@b@    throws FileUploadException@b@  {@b@    List items = new ArrayList();@b@    boolean successful = false;@b@    try {@b@      FileItemIterator iter = getItemIterator(ctx);@b@      FileItemFactory fac = getFileItemFactory();@b@      if (fac == null)@b@        throw new NullPointerException("No FileItemFactory has been set.");@b@      FileItem fileItem;@b@      while (iter.hasNext()) {@b@        item = iter.next();@b@@b@        String fileName = ((FileItemIteratorImpl.FileItemStreamImpl)item).name;@b@        fileItem = fac.createItem(item.getFieldName(), item.getContentType(), item.isFormField(), fileName);@b@@b@        items.add(fileItem);@b@        try {@b@          Streams.copy(item.openStream(), fileItem.getOutputStream(), true);@b@        } catch (FileUploadIOException e) {@b@          throw ((FileUploadException)e.getCause());@b@        } catch (IOException e) {@b@          throw new IOFileUploadException(String.format("Processing of %s request failed. %s", new Object[] { "multipart/form-data", e.getMessage() }), e);@b@        }@b@@b@        FileItemHeaders fih = item.getHeaders();@b@        fileItem.setHeaders(fih);@b@      }@b@      successful = true;@b@      FileItemStream item = items;@b@      Iterator i$;@b@      return item;@b@    }@b@    catch (FileUploadIOException e)@b@    {@b@    }@b@    catch (IOException e)@b@    {@b@    }@b@    finally@b@    {@b@      if (!(successful))@b@        for (FileItem fileItem : items)@b@          try {@b@            fileItem.delete();@b@          }@b@          catch (Throwable e)@b@          {@b@          }@b@    }@b@  }@b@@b@  public Map<String, List<FileItem>> parseParameterMap(RequestContext ctx)@b@    throws FileUploadException@b@  {@b@    List items = parseRequest(ctx);@b@    Map itemsMap = new HashMap(items.size());@b@@b@    for (FileItem fileItem : items) {@b@      String fieldName = fileItem.getFieldName();@b@      List mappedItems = (List)itemsMap.get(fieldName);@b@@b@      if (mappedItems == null) {@b@        mappedItems = new ArrayList();@b@        itemsMap.put(fieldName, mappedItems);@b@      }@b@@b@      mappedItems.add(fileItem);@b@    }@b@@b@    return itemsMap;@b@  }@b@@b@  protected byte[] getBoundary(String contentType)@b@  {@b@    ParameterParser parser = new ParameterParser();@b@    parser.setLowerCaseNames(true);@b@@b@    Map params = parser.parse(contentType, new char[] { ';', ',' });@b@    String boundaryStr = (String)params.get("boundary");@b@@b@    if (boundaryStr == null)@b@      return null;@b@    byte[] boundary;@b@    try@b@    {@b@      boundary = boundaryStr.getBytes("ISO-8859-1");@b@    } catch (UnsupportedEncodingException e) {@b@      boundary = boundaryStr.getBytes();@b@    }@b@    return boundary;@b@  }@b@@b@  @Deprecated@b@  protected String getFileName(Map<String, String> headers)@b@  {@b@    return getFileName(getHeader(headers, "Content-disposition"));@b@  }@b@@b@  protected String getFileName(FileItemHeaders headers)@b@  {@b@    return getFileName(headers.getHeader("Content-disposition"));@b@  }@b@@b@  private String getFileName(String pContentDisposition)@b@  {@b@    String fileName = null;@b@    if (pContentDisposition != null) {@b@      String cdl = pContentDisposition.toLowerCase(Locale.ENGLISH);@b@      if ((cdl.startsWith("form-data")) || (cdl.startsWith("attachment"))) {@b@        ParameterParser parser = new ParameterParser();@b@        parser.setLowerCaseNames(true);@b@@b@        Map params = parser.parse(pContentDisposition, ';');@b@        if (params.containsKey("filename")) {@b@          fileName = (String)params.get("filename");@b@          if (fileName != null) {@b@            fileName = fileName.trim();@b@          }@b@          else@b@          {@b@            fileName = "";@b@          }@b@        }@b@      }@b@    }@b@    return fileName;@b@  }@b@@b@  protected String getFieldName(FileItemHeaders headers)@b@  {@b@    return getFieldName(headers.getHeader("Content-disposition"));@b@  }@b@@b@  private String getFieldName(String pContentDisposition)@b@  {@b@    String fieldName = null;@b@    if ((pContentDisposition != null) && (pContentDisposition.toLowerCase(Locale.ENGLISH).startsWith("form-data")))@b@    {@b@      ParameterParser parser = new ParameterParser();@b@      parser.setLowerCaseNames(true);@b@@b@      Map params = parser.parse(pContentDisposition, ';');@b@      fieldName = (String)params.get("name");@b@      if (fieldName != null) {@b@        fieldName = fieldName.trim();@b@      }@b@    }@b@    return fieldName;@b@  }@b@@b@  @Deprecated@b@  protected String getFieldName(Map<String, String> headers)@b@  {@b@    return getFieldName(getHeader(headers, "Content-disposition"));@b@  }@b@@b@  @Deprecated@b@  protected FileItem createItem(Map<String, String> headers, boolean isFormField)@b@    throws FileUploadException@b@  {@b@    return getFileItemFactory().createItem(getFieldName(headers), getHeader(headers, "Content-type"), isFormField, getFileName(headers));@b@  }@b@@b@  protected FileItemHeaders getParsedHeaders(String headerPart)@b@  {@b@    int len = headerPart.length();@b@    FileItemHeadersImpl headers = newFileItemHeaders();@b@    int start = 0;@b@    while (true) {@b@      int end = parseEndOfLine(headerPart, start);@b@      if (start == end) {@b@        break;@b@      }@b@      StringBuilder header = new StringBuilder(headerPart.substring(start, end));@b@      start = end + 2;@b@      while (start < len) {@b@        int nonWs = start;@b@        while (nonWs < len) {@b@          char c = headerPart.charAt(nonWs);@b@          if ((c != ' ') && (c != '\t')) {@b@            break;@b@          }@b@          ++nonWs;@b@        }@b@        if (nonWs == start) {@b@          break;@b@        }@b@@b@        end = parseEndOfLine(headerPart, nonWs);@b@        header.append(" ").append(headerPart.substring(nonWs, end));@b@        start = end + 2;@b@      }@b@      parseHeaderLine(headers, header.toString());@b@    }@b@    return headers;@b@  }@b@@b@  protected FileItemHeadersImpl newFileItemHeaders()@b@  {@b@    return new FileItemHeadersImpl();@b@  }@b@@b@  @Deprecated@b@  protected Map<String, String> parseHeaders(String headerPart)@b@  {@b@    FileItemHeaders headers = getParsedHeaders(headerPart);@b@    Map result = new HashMap();@b@    for (Iterator iter = headers.getHeaderNames(); iter.hasNext(); ) {@b@      String headerName = (String)iter.next();@b@      Iterator iter2 = headers.getHeaders(headerName);@b@      StringBuilder headerValue = new StringBuilder((String)iter2.next());@b@      while (iter2.hasNext()) {@b@        headerValue.append(",").append((String)iter2.next());@b@      }@b@      result.put(headerName, headerValue.toString());@b@    }@b@    return result;@b@  }@b@@b@  private int parseEndOfLine(String headerPart, int end)@b@  {@b@    int index = end;@b@    while (true) {@b@      int offset = headerPart.indexOf(13, index);@b@      if ((offset == -1) || (offset + 1 >= headerPart.length())) {@b@        throw new IllegalStateException("Expected headers to be terminated by an empty line.");@b@      }@b@@b@      if (headerPart.charAt(offset + 1) == '\n') {@b@        return offset;@b@      }@b@      index = offset + 1;@b@    }@b@  }@b@@b@  private void parseHeaderLine(FileItemHeadersImpl headers, String header)@b@  {@b@    int colonOffset = header.indexOf(58);@b@    if (colonOffset == -1)@b@    {@b@      return;@b@    }@b@    String headerName = header.substring(0, colonOffset).trim();@b@    String headerValue = header.substring(header.indexOf(58) + 1).trim();@b@@b@    headers.addHeader(headerName, headerValue);@b@  }@b@@b@  @Deprecated@b@  protected final String getHeader(Map<String, String> headers, String name)@b@  {@b@    return ((String)headers.get(name.toLowerCase(Locale.ENGLISH)));@b@  }@b@@b@  public ProgressListener getProgressListener()@b@  {@b@    return this.listener;@b@  }@b@@b@  public void setProgressListener(ProgressListener pListener)@b@  {@b@    this.listener = pListener;@b@  }@b@@b@  public static class FileSizeLimitExceededException extends FileUploadBase.SizeException@b@  {@b@    private static final long serialVersionUID = 8150776562029630058L;@b@    private String fileName;@b@    private String fieldName;@b@@b@    public FileSizeLimitExceededException(String message, long actual, long permitted)@b@    {@b@      super(message, actual, permitted);@b@    }@b@@b@    public String getFileName()@b@    {@b@      return this.fileName;@b@    }@b@@b@    public void setFileName(String pFileName)@b@    {@b@      this.fileName = pFileName;@b@    }@b@@b@    public String getFieldName()@b@    {@b@      return this.fieldName;@b@    }@b@@b@    public void setFieldName(String pFieldName)@b@    {@b@      this.fieldName = pFieldName;@b@    }@b@  }@b@@b@  public static class SizeLimitExceededException extends FileUploadBase.SizeException@b@  {@b@    private static final long serialVersionUID = -2474893167098052828L;@b@@b@    @Deprecated@b@    public SizeLimitExceededException()@b@    {@b@      this(null, 0L, 0L);@b@    }@b@@b@    @Deprecated@b@    public SizeLimitExceededException(String message)@b@    {@b@      this(message, 0L, 0L);@b@    }@b@@b@    public SizeLimitExceededException(String message, long actual, long permitted)@b@    {@b@      super(message, actual, permitted);@b@    }@b@  }@b@@b@  @Deprecated@b@  public static class UnknownSizeException extends FileUploadException@b@  {@b@    private static final long serialVersionUID = 7062279004812015273L;@b@@b@    public UnknownSizeException()@b@    {@b@    }@b@@b@    public UnknownSizeException(String message)@b@    {@b@      super(message);@b@    }@b@  }@b@@b@  protected static abstract class SizeException extends FileUploadException@b@  {@b@    private static final long serialVersionUID = -8776225574705254126L;@b@    private final long actual;@b@    private final long permitted;@b@@b@    protected SizeException(String message, long actual, long permitted)@b@    {@b@      super(message);@b@      this.actual = actual;@b@      this.permitted = permitted;@b@    }@b@@b@    public long getActualSize()@b@    {@b@      return this.actual;@b@    }@b@@b@    public long getPermittedSize()@b@    {@b@      return this.permitted;@b@    }@b@  }@b@@b@  public static class IOFileUploadException extends FileUploadException@b@  {@b@    private static final long serialVersionUID = 1749796615868477269L;@b@    private final IOException cause;@b@@b@    public IOFileUploadException(String pMsg, IOException pException)@b@    {@b@      super(pMsg);@b@      this.cause = pException;@b@    }@b@@b@    public Throwable getCause()@b@    {@b@      return this.cause;@b@    }@b@  }@b@@b@  public static class InvalidContentTypeException extends FileUploadException@b@  {@b@    private static final long serialVersionUID = -9073026332015646668L;@b@@b@    public InvalidContentTypeException()@b@    {@b@    }@b@@b@    public InvalidContentTypeException(String message)@b@    {@b@      super(message);@b@    }@b@@b@    public InvalidContentTypeException(String msg, Throwable cause)@b@    {@b@      super(msg, cause);@b@    }@b@  }@b@@b@  public static class FileUploadIOException extends IOException@b@  {@b@    private static final long serialVersionUID = -7047616958165584154L;@b@    private final FileUploadException cause;@b@@b@    public FileUploadIOException(FileUploadException pCause)@b@    {@b@      this.cause = pCause;@b@    }@b@@b@    public Throwable getCause()@b@    {@b@      return this.cause;@b@    }@b@  }@b@@b@  private class FileItemIteratorImpl@b@    implements FileItemIterator@b@  {@b@    private final MultipartStream multi;@b@    private final MultipartStream.ProgressNotifier notifier;@b@    private final byte[] boundary;@b@    private FileItemStreamImpl currentItem;@b@    private String currentFieldName;@b@    private boolean skipPreamble;@b@    private boolean itemValid;@b@    private boolean eof;@b@@b@    FileItemIteratorImpl(RequestContext ctx)@b@      throws FileUploadException, IOException@b@    {@b@      if (ctx == null) {@b@        throw new NullPointerException("ctx parameter");@b@      }@b@@b@      String contentType = ctx.getContentType();@b@      if ((null == contentType) || (!(contentType.toLowerCase(Locale.ENGLISH).startsWith("multipart/"))))@b@      {@b@        throw new FileUploadBase.InvalidContentTypeException(String.format("the request doesn't contain a %s or %s stream, content type header is %s", new Object[] { "multipart/form-data", "multipart/mixed", contentType }));@b@      }@b@@b@      InputStream input = ctx.getInputStream();@b@@b@      int contentLengthInt = ctx.getContentLength();@b@@b@      long requestSize = contentLengthInt;@b@@b@      if (FileUploadBase.this.sizeMax >= 0L) {@b@        if ((requestSize != -1L) && (requestSize > FileUploadBase.this.sizeMax)) {@b@          throw new FileUploadBase.SizeLimitExceededException(String.format("the request was rejected because its size (%s) exceeds the configured maximum (%s)", new Object[] { Long.valueOf(requestSize), Long.valueOf(FileUploadBase.access$400(FileUploadBase.this)) }), requestSize, FileUploadBase.this.sizeMax);@b@        }@b@@b@        input = new LimitedInputStream(input, FileUploadBase.this.sizeMax, FileUploadBase.this)@b@        {@b@          protected void raiseError(long pSizeMax, long pCount) throws IOException@b@          {@b@            FileUploadException ex = new FileUploadBase.SizeLimitExceededException(String.format("the request was rejected because its size (%s) exceeds the configured maximum (%s)", new Object[] { Long.valueOf(pCount), Long.valueOf(pSizeMax) }), pCount, pSizeMax);@b@@b@            throw new FileUploadBase.FileUploadIOException(ex);@b@          }@b@        };@b@      }@b@@b@      String charEncoding = FileUploadBase.this.headerEncoding;@b@      if (charEncoding == null) {@b@        charEncoding = ctx.getCharacterEncoding();@b@      }@b@@b@      this.boundary = FileUploadBase.this.getBoundary(contentType);@b@      if (this.boundary == null) {@b@        throw new FileUploadException("the request was rejected because no multipart boundary was found");@b@      }@b@@b@      this.notifier = new MultipartStream.ProgressNotifier(FileUploadBase.this.listener, requestSize);@b@      try {@b@        this.multi = new MultipartStream(input, this.boundary, this.notifier);@b@      } catch (IllegalArgumentException iae) {@b@        throw new FileUploadBase.InvalidContentTypeException(String.format("The boundary specified in the %s header is too long", new Object[] { "Content-type" }), iae);@b@      }@b@@b@      this.multi.setHeaderEncoding(charEncoding);@b@@b@      this.skipPreamble = true;@b@      findNextItem();@b@    }@b@@b@    private boolean findNextItem()@b@      throws IOException@b@    {@b@      if (this.eof) {@b@        return false;@b@      }@b@      if (this.currentItem != null) {@b@        this.currentItem.close();@b@        this.currentItem = null;@b@      }@b@      while (true)@b@      {@b@        boolean nextPart;@b@        if (this.skipPreamble)@b@          nextPart = this.multi.skipPreamble();@b@        else {@b@          nextPart = this.multi.readBoundary();@b@        }@b@        if (!(nextPart)) {@b@          if (this.currentFieldName == null)@b@          {@b@            this.eof = true;@b@            return false;@b@          }@b@@b@          this.multi.setBoundary(this.boundary);@b@          this.currentFieldName = null;@b@        }@b@@b@        FileItemHeaders headers = FileUploadBase.this.getParsedHeaders(this.multi.readHeaders());@b@        if (this.currentFieldName == null)@b@        {@b@          String fieldName = FileUploadBase.this.getFieldName(headers);@b@          if (fieldName != null) {@b@            String subContentType = headers.getHeader("Content-type");@b@            if ((subContentType != null) && (subContentType.toLowerCase(Locale.ENGLISH).startsWith("multipart/mixed")))@b@            {@b@              this.currentFieldName = fieldName;@b@@b@              byte[] subBoundary = FileUploadBase.this.getBoundary(subContentType);@b@              this.multi.setBoundary(subBoundary);@b@              this.skipPreamble = true;@b@            }@b@@b@            String fileName = FileUploadBase.this.getFileName(headers);@b@            this.currentItem = new FileItemStreamImpl(fileName, fieldName, headers.getHeader("Content-type"), fileName == null, getContentLength(headers));@b@@b@            this.currentItem.setHeaders(headers);@b@            this.notifier.noteItem();@b@            this.itemValid = true;@b@            return true;@b@          }@b@        } else {@b@          String fileName = FileUploadBase.this.getFileName(headers);@b@          if (fileName != null) {@b@            this.currentItem = new FileItemStreamImpl(fileName, this.currentFieldName, headers.getHeader("Content-type"), false, getContentLength(headers));@b@@b@            this.currentItem.setHeaders(headers);@b@            this.notifier.noteItem();@b@            this.itemValid = true;@b@            return true;@b@          }@b@        }@b@        this.multi.discardBodyData();@b@      }@b@    }@b@@b@    private long getContentLength(FileItemHeaders pHeaders) {@b@      try {@b@        return Long.parseLong(pHeaders.getHeader("Content-length")); } catch (Exception e) {@b@      }@b@      return -1L;@b@    }@b@@b@    public boolean hasNext()@b@      throws FileUploadException, IOException@b@    {@b@      if (this.eof) {@b@        return false;@b@      }@b@      if (this.itemValid)@b@        return true;@b@      try@b@      {@b@        return findNextItem();@b@      }@b@      catch (FileUploadBase.FileUploadIOException e) {@b@        throw ((FileUploadException)e.getCause());@b@      }@b@    }@b@@b@    public FileItemStream next()@b@      throws FileUploadException, IOException@b@    {@b@      if ((this.eof) || ((!(this.itemValid)) && (!(hasNext())))) {@b@        throw new NoSuchElementException();@b@      }@b@      this.itemValid = false;@b@      return this.currentItem;@b@    }@b@@b@    class FileItemStreamImpl@b@      implements FileItemStream@b@    {@b@      private final String contentType;@b@      private final String fieldName;@b@      private final String name;@b@      private final boolean formField;@b@      private final InputStream stream;@b@      private boolean opened;@b@      private FileItemHeaders headers;@b@@b@      FileItemStreamImpl(String pName, String pFieldName, String pContentType, boolean pFormField, long pContentLength)@b@        throws IOException@b@      {@b@        this.name = pName;@b@        this.fieldName = pFieldName;@b@        this.contentType = pContentType;@b@        this.formField = pFormField;@b@        MultipartStream.ItemInputStream itemStream = FileUploadBase.FileItemIteratorImpl.this.multi.newInputStream();@b@        InputStream istream = itemStream;@b@        if (FileUploadBase.this.fileSizeMax != -1L) {@b@          if ((pContentLength != -1L) && (pContentLength > FileUploadBase.this.fileSizeMax))@b@          {@b@            FileUploadBase.FileSizeLimitExceededException e = new FileUploadBase.FileSizeLimitExceededException(String.format("The field %s exceeds its maximum permitted size of %s bytes.", new Object[] { this.fieldName, Long.valueOf(FileUploadBase.access$200(FileUploadBase.this)) }), pContentLength, FileUploadBase.this.fileSizeMax);@b@@b@            e.setFileName(pName);@b@            e.setFieldName(pFieldName);@b@            throw new FileUploadBase.FileUploadIOException(e);@b@          }@b@          istream = new LimitedInputStream(istream, FileUploadBase.this.fileSizeMax, FileUploadBase.FileItemIteratorImpl.this, itemStream)@b@          {@b@            protected void raiseError(long pSizeMax, long pCount) throws IOException@b@            {@b@              this.val$itemStream.close(true);@b@              FileUploadBase.FileSizeLimitExceededException e = new FileUploadBase.FileSizeLimitExceededException(String.format("The field %s exceeds its maximum permitted size of %s bytes.", new Object[] { FileUploadBase.FileItemIteratorImpl.FileItemStreamImpl.access$300(FileUploadBase.FileItemIteratorImpl.FileItemStreamImpl.this), Long.valueOf(pSizeMax) }), pCount, pSizeMax);@b@@b@              e.setFieldName(FileUploadBase.FileItemIteratorImpl.FileItemStreamImpl.this.fieldName);@b@              e.setFileName(FileUploadBase.FileItemIteratorImpl.FileItemStreamImpl.this.name);@b@              throw new FileUploadBase.FileUploadIOException(e);@b@            }@b@          };@b@        }@b@        this.stream = istream;@b@      }@b@@b@      public String getContentType()@b@      {@b@        return this.contentType;@b@      }@b@@b@      public String getFieldName()@b@      {@b@        return this.fieldName;@b@      }@b@@b@      public String getName()@b@      {@b@        return Streams.checkFileName(this.name);@b@      }@b@@b@      public boolean isFormField()@b@      {@b@        return this.formField;@b@      }@b@@b@      public InputStream openStream()@b@        throws IOException@b@      {@b@        if (this.opened) {@b@          throw new IllegalStateException("The stream was already opened.");@b@        }@b@@b@        if (((Closeable)this.stream).isClosed()) {@b@          throw new FileItemStream.ItemSkippedException();@b@        }@b@        return this.stream;@b@      }@b@@b@      void close()@b@        throws IOException@b@      {@b@        this.stream.close();@b@      }@b@@b@      public FileItemHeaders getHeaders()@b@      {@b@        return this.headers;@b@      }@b@@b@      public void setHeaders(FileItemHeaders pHeaders)@b@      {@b@        this.headers = pHeaders;@b@      }@b@    }@b@  }@b@}

2.ServletFileUpload

package org.apache.commons.fileupload.servlet;@b@@b@import java.io.IOException;@b@import java.util.List;@b@import java.util.Map;@b@import javax.servlet.http.HttpServletRequest;@b@import org.apache.commons.fileupload.FileItem;@b@import org.apache.commons.fileupload.FileItemFactory;@b@import org.apache.commons.fileupload.FileItemIterator;@b@import org.apache.commons.fileupload.FileUpload;@b@import org.apache.commons.fileupload.FileUploadBase;@b@import org.apache.commons.fileupload.FileUploadException;@b@@b@public class ServletFileUpload extends FileUpload@b@{@b@  private static final String POST_METHOD = "POST";@b@@b@  public static final boolean isMultipartContent(HttpServletRequest request)@b@  {@b@    if (!("POST".equalsIgnoreCase(request.getMethod()))) {@b@      return false;@b@    }@b@    return FileUploadBase.isMultipartContent(new ServletRequestContext(request));@b@  }@b@@b@  public ServletFileUpload()@b@  {@b@  }@b@@b@  public ServletFileUpload(FileItemFactory fileItemFactory)@b@  {@b@    super(fileItemFactory);@b@  }@b@@b@  public List<FileItem> parseRequest(HttpServletRequest request)@b@    throws FileUploadException@b@  {@b@    return parseRequest(new ServletRequestContext(request));@b@  }@b@@b@  public Map<String, List<FileItem>> parseParameterMap(HttpServletRequest request)@b@    throws FileUploadException@b@  {@b@    return parseParameterMap(new ServletRequestContext(request));@b@  }@b@@b@  public FileItemIterator getItemIterator(HttpServletRequest request)@b@    throws FileUploadException, IOException@b@  {@b@    return super.getItemIterator(new ServletRequestContext(request));@b@  }@b@}

3.Streams

package org.apache.commons.fileupload.util;@b@@b@import java.io.ByteArrayOutputStream;@b@import java.io.IOException;@b@import java.io.InputStream;@b@import java.io.OutputStream;@b@import org.apache.commons.fileupload.InvalidFileNameException;@b@import org.apache.commons.io.IOUtils;@b@@b@public final class Streams@b@{@b@  private static final int DEFAULT_BUFFER_SIZE = 8192;@b@@b@  public static long copy(InputStream inputStream, OutputStream outputStream, boolean closeOutputStream)@b@    throws IOException@b@  {@b@    return copy(inputStream, outputStream, closeOutputStream, new byte[8192]);@b@  }@b@@b@  public static long copy(InputStream inputStream, OutputStream outputStream, boolean closeOutputStream, byte[] buffer)@b@    throws IOException@b@  {@b@    OutputStream out = outputStream;@b@    InputStream in = inputStream;@b@    try {@b@      long total = 0L;@b@      while (true) {@b@        res = in.read(buffer);@b@        if (res == -1) {@b@          break;@b@        }@b@        if (res > 0) {@b@          total += res;@b@          if (out != null) {@b@            out.write(buffer, 0, res);@b@          }@b@        }@b@      }@b@      if (out != null) {@b@        if (closeOutputStream)@b@          out.close();@b@        else {@b@          out.flush();@b@        }@b@        out = null;@b@      }@b@      in.close();@b@      in = null;@b@      int res = total;@b@@b@      return res;@b@    }@b@    finally@b@    {@b@      IOUtils.closeQuietly(in);@b@      if (closeOutputStream)@b@        IOUtils.closeQuietly(out);@b@    }@b@  }@b@@b@  public static String asString(InputStream inputStream)@b@    throws IOException@b@  {@b@    ByteArrayOutputStream baos = new ByteArrayOutputStream();@b@    copy(inputStream, baos, true);@b@    return baos.toString();@b@  }@b@@b@  public static String asString(InputStream inputStream, String encoding)@b@    throws IOException@b@  {@b@    ByteArrayOutputStream baos = new ByteArrayOutputStream();@b@    copy(inputStream, baos, true);@b@    return baos.toString(encoding);@b@  }@b@@b@  public static String checkFileName(String fileName)@b@  {@b@    if ((fileName != null) && (fileName.indexOf(0) != -1))@b@    {@b@      StringBuilder sb = new StringBuilder();@b@      for (int i = 0; i < fileName.length(); ++i) {@b@        char c = fileName.charAt(i);@b@        switch (c)@b@        {@b@        case '\0':@b@          sb.append("\\0");@b@          break;@b@        default:@b@          sb.append(c);@b@        }@b@      }@b@@b@      throw new InvalidFileNameException(fileName, "Invalid file name: " + sb);@b@    }@b@@b@    return fileName;@b@  }@b@}
<<热门下载>>