Example usage for org.apache.commons.fileupload FileItem getOutputStream

List of usage examples for org.apache.commons.fileupload FileItem getOutputStream

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItem getOutputStream.

Prototype

OutputStream getOutputStream() throws IOException;

Source Link

Document

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

Usage

From source file:org.orbeon.oxf.processor.generator.RequestGenerator.java

@Override
public ProcessorOutput createOutput(String name) {
    final ProcessorOutput output = new DigestTransformerOutputImpl(RequestGenerator.this, name) {
        public void readImpl(final PipelineContext pipelineContext, XMLReceiver xmlReceiver) {
            final State state = (State) getFilledOutState(pipelineContext);
            // Transform the resulting document into SAX

            TransformerUtils.sourceToSAX(new DocumentSource(state.requestDocument),
                    new ForwardingXMLReceiver(xmlReceiver) {
                        @Override
                        public void startElement(String uri, String localname, String qName,
                                Attributes attributes) throws SAXException {
                            try {
                                if (REQUEST_PRIVATE_NAMESPACE_URI.equals(uri)) {
                                    // Special treatment for this element
                                    if (FILE_ITEM_ELEMENT.equals(qName)) {
                                        // Marker for file item

                                        final String parameterName = attributes
                                                .getValue(PARAMETER_NAME_ATTRIBUTE);
                                        final int parameterPosition = Integer
                                                .parseInt(attributes.getValue(PARAMETER_POSITION_ATTRIBUTE));
                                        final FileItem fileItem = (FileItem) ((Object[]) getRequest(
                                                pipelineContext).getParameterMap()
                                                        .get(parameterName))[parameterPosition];

                                        final AttributesImpl newAttributes = new AttributesImpl();
                                        super.startPrefixMapping(XMLConstants.XSI_PREFIX, XMLConstants.XSI_URI);
                                        super.startPrefixMapping(XMLConstants.XSD_PREFIX, XMLConstants.XSD_URI);
                                        newAttributes.addAttribute(XMLConstants.XSI_URI, "type", "xsi:type",
                                                "CDATA",
                                                useBase64(pipelineContext, fileItem)
                                                        ? XMLConstants.XS_BASE64BINARY_QNAME.getQualifiedName()
                                                        : XMLConstants.XS_ANYURI_QNAME.getQualifiedName());
                                        super.startElement("", "value", "value", newAttributes);
                                        writeFileItem(pipelineContext, fileItem, state.isSessionScope,
                                                useBase64(pipelineContext, fileItem), getXMLReceiver());
                                        super.endElement("", "value", "value");
                                        super.endPrefixMapping(XMLConstants.XSD_PREFIX);
                                        super.endPrefixMapping(XMLConstants.XSI_PREFIX);
                                    }/*  w ww . j av a2 s  . co  m*/
                                } else if (localname.equals("body") && uri.equals("")) {
                                    // Marker for request body

                                    // Read InputStream into FileItem object, if not already present

                                    // We do this so we can read the body multiple times, if needed.
                                    // For large files, there will be a performance hit. If we knew
                                    // we didn't need to read it multiple times, we could avoid
                                    // saving the stream, but practically, it can happen, and it is
                                    // convenient.
                                    final Context context = getContext(pipelineContext);
                                    if (context.bodyFileItem != null
                                            || getRequest(pipelineContext).getInputStream() != null) {

                                        final ExternalContext.Request request = getRequest(pipelineContext);

                                        if (context.bodyFileItem == null) {
                                            final FileItem fileItem = new DiskFileItemFactory(
                                                    getMaxMemorySizeProperty(),
                                                    SystemUtils.getTemporaryDirectory()).createItem("dummy",
                                                            "dummy", false, null);
                                            pipelineContext.addContextListener(
                                                    new PipelineContext.ContextListenerAdapter() {
                                                        public void contextDestroyed(boolean success) {
                                                            fileItem.delete();
                                                        }
                                                    });
                                            final OutputStream outputStream = fileItem.getOutputStream();
                                            NetUtils.copyStream(request.getInputStream(), outputStream);
                                            outputStream.close();
                                            context.bodyFileItem = fileItem;
                                        }
                                        // Serialize the stream into the body element
                                        final AttributesImpl newAttributes = new AttributesImpl();
                                        super.startPrefixMapping(XMLConstants.XSI_PREFIX, XMLConstants.XSI_URI);
                                        super.startPrefixMapping(XMLConstants.XSD_PREFIX, XMLConstants.XSD_URI);
                                        newAttributes.addAttribute(XMLConstants.XSI_URI, "type", "xsi:type",
                                                "CDATA",
                                                useBase64(pipelineContext, context.bodyFileItem)
                                                        ? XMLConstants.XS_BASE64BINARY_QNAME.getQualifiedName()
                                                        : XMLConstants.XS_ANYURI_QNAME.getQualifiedName());
                                        super.startElement(uri, localname, qName, newAttributes);
                                        final String uriOrNull = writeFileItem(pipelineContext,
                                                context.bodyFileItem, state.isSessionScope,
                                                useBase64(pipelineContext, context.bodyFileItem),
                                                getXMLReceiver());
                                        super.endElement(uri, localname, qName);
                                        super.endPrefixMapping(XMLConstants.XSD_PREFIX);
                                        super.endPrefixMapping(XMLConstants.XSI_PREFIX);

                                        // If the body is available as a URL, store it into the pipeline context.
                                        // This is done so that native code can access the body even if it has been read
                                        // already. Possibly, this could be handled more transparently by ExternalContext,
                                        // so that Request.getInputStream() works even upon multiple reads.
                                        // NOTE 2013-05-30: We used to store this into the request, but request attributes
                                        // are forwarded by LocalRequest. This means that a forwarded-to request might get
                                        // the wrong body! Instead, we now use PipelineContext, which is scoped to be per
                                        // request. Again, if ExternalContext was handling this, we could just leave it to
                                        // ExternalContext.
                                        if (uriOrNull != null)
                                            pipelineContext.setAttribute(BODY_REQUEST_ATTRIBUTE, uriOrNull);
                                    }
                                } else {
                                    super.startElement(uri, localname, qName, attributes);
                                }
                            } catch (IOException e) {
                                throw new OXFException(e);
                            }
                        }

                        @Override
                        public void endElement(String uri, String localname, String qName) throws SAXException {
                            if (REQUEST_PRIVATE_NAMESPACE_URI.equals(uri)
                                    || localname.equals("body") && uri.equals("")) {
                                // Ignore end element
                            } else {
                                super.endElement(uri, localname, qName);
                            }
                        }
                    });
        }

        protected boolean fillOutState(PipelineContext pipelineContext, DigestState digestState) {
            final State state = (State) digestState;
            if (state.requestDocument == null) {
                // Read config document
                final Document config = readCacheInputAsDOM4J(pipelineContext, INPUT_CONFIG);

                // Try to find stream-type attribute
                final QName streamTypeQName = Dom4jUtils.extractAttributeValueQName(config.getRootElement(),
                        "stream-type");
                if (streamTypeQName != null && !(streamTypeQName.equals(XMLConstants.XS_BASE64BINARY_QNAME)
                        || streamTypeQName.equals(XMLConstants.XS_ANYURI_QNAME)))
                    throw new OXFException(
                            "Invalid value for stream-type attribute: " + streamTypeQName.getQualifiedName());
                state.requestedStreamType = streamTypeQName;
                state.isSessionScope = "session".equals(config.getRootElement().attributeValue("stream-scope"));

                // Read and store request
                state.requestDocument = readRequestAsDOM4J(pipelineContext, config);

                // Check if the body was requested
                state.bodyRequested = XPathUtils.selectSingleNode(state.requestDocument, "/*/body") != null;
            }
            final Context context = getContext(pipelineContext);
            return !context.hasUpload && !state.bodyRequested;
        }

        protected byte[] computeDigest(PipelineContext pipelineContext, DigestState digestState) {
            final State state = (State) digestState;
            return DigestContentHandler.getDigest(new DocumentSource(state.requestDocument));
        }
    };
    addOutput(name, output);
    return output;
}

From source file:org.orbeon.oxf.processor.serializer.FileSerializer.java

/**
 * Case where a response must be generated.
 *//*www  . j av  a  2 s  .c  o  m*/
@Override
public ProcessorOutput createOutput(String name) {

    final ProcessorOutput output = new ProcessorOutputImpl(FileSerializer.this, name) {
        public void readImpl(PipelineContext pipelineContext, XMLReceiver xmlReceiver) {
            OutputStream fileOutputStream = null;
            try {
                //Get the input and config
                final Config config = getConfig(pipelineContext);
                final ProcessorInput dataInput = getInputByName(INPUT_DATA);

                // Determine scope
                final int scope;
                if ("request".equals(config.getScope())) {
                    scope = NetUtils.REQUEST_SCOPE;
                } else if ("session".equals(config.getScope())) {
                    scope = NetUtils.SESSION_SCOPE;
                } else if ("application".equals(config.getScope())) {
                    scope = NetUtils.APPLICATION_SCOPE;
                } else {
                    throw new OXFException("Invalid context requested: " + config.getScope());
                }

                // We use the commons fileupload utilities to write to file
                final FileItem fileItem = NetUtils.prepareFileItem(scope, logger);
                fileOutputStream = fileItem.getOutputStream();
                writeToFile(pipelineContext, config, dataInput, fileOutputStream);

                // Create file if it doesn't exist
                final File storeLocation = ((DiskFileItem) fileItem).getStoreLocation();
                storeLocation.createNewFile();

                // Get the url of the file
                final String resultURL;
                {
                    final String localURL = ((DiskFileItem) fileItem).getStoreLocation().toURI().toString();
                    if ("session".equals(config.getScope()) && config.isProxyResult())
                        resultURL = XFormsResourceServer.jProxyURI(localURL, config.getRequestedContentType());
                    else
                        resultURL = localURL;
                }

                xmlReceiver.startDocument();
                xmlReceiver.startElement("", "url", "url", SAXUtils.EMPTY_ATTRIBUTES);
                xmlReceiver.characters(resultURL.toCharArray(), 0, resultURL.length());
                xmlReceiver.endElement("", "url", "url");
                xmlReceiver.endDocument();
            } catch (SAXException e) {
                throw new OXFException(e);
            } catch (IOException e) {
                throw new OXFException(e);
            } finally {
                if (fileOutputStream != null) {
                    try {
                        fileOutputStream.close();
                    } catch (IOException e) {
                        throw new OXFException(e);
                    }
                }
            }
        }
    };
    addOutput(name, output);
    return output;
}

From source file:org.orbeon.oxf.processor.zip.UnzipProcessor.java

@Override
public ProcessorOutput createOutput(String name) {
    final ProcessorOutput output = new ProcessorOutputImpl(UnzipProcessor.this, name) {

        public void readImpl(PipelineContext context, XMLReceiver xmlReceiver) {
            try {
                // Read input in a temporary file
                final File temporaryZipFile;
                {/*w ww .ja  va 2 s . c om*/
                    final FileItem fileItem = NetUtils.prepareFileItem(NetUtils.REQUEST_SCOPE, logger);
                    final OutputStream fileOutputStream = fileItem.getOutputStream();
                    readInputAsSAX(context, getInputByName(INPUT_DATA),
                            new BinaryTextXMLReceiver(fileOutputStream));
                    temporaryZipFile = ((DiskFileItem) fileItem).getStoreLocation();
                }

                xmlReceiver.startDocument();
                // <files>
                xmlReceiver.startElement("", "files", "files", SAXUtils.EMPTY_ATTRIBUTES);
                ZipFile zipFile = new ZipFile(temporaryZipFile);
                for (Enumeration entries = zipFile.entries(); entries.hasMoreElements();) {
                    // Go through each entry in the zip file
                    ZipEntry zipEntry = (ZipEntry) entries.nextElement();
                    // Get file name
                    String fileName = zipEntry.getName();
                    long fileSize = zipEntry.getSize();
                    String fileTime = DateUtils.DateTime().print(zipEntry.getTime());

                    InputStream entryInputStream = zipFile.getInputStream(zipEntry);
                    String uri = NetUtils.inputStreamToAnyURI(entryInputStream, NetUtils.REQUEST_SCOPE, logger);
                    // <file name="filename.ext">uri</file>
                    AttributesImpl fileAttributes = new AttributesImpl();
                    fileAttributes.addAttribute("", "name", "name", "CDATA", fileName);
                    fileAttributes.addAttribute("", "size", "size", "CDATA", Long.toString(fileSize));
                    fileAttributes.addAttribute("", "dateTime", "dateTime", "CDATA", fileTime);
                    xmlReceiver.startElement("", "file", "file", fileAttributes);
                    xmlReceiver.characters(uri.toCharArray(), 0, uri.length());
                    // </file>
                    xmlReceiver.endElement("", "file", "file");
                }
                // </files>
                xmlReceiver.endElement("", "files", "files");
                xmlReceiver.endDocument();

            } catch (IOException e) {
                throw new OXFException(e);
            } catch (SAXException e) {
                throw new OXFException(e);
            }
        }

        // We don't do any caching here since the file we produce are temporary. So we don't want a processor
        // downstream to keep a reference to a document that contains temporary URI that have since been deleted.

    };
    addOutput(name, output);
    return output;
}

From source file:org.orbeon.oxf.processor.zip.ZipProcessor.java

@Override
public ProcessorOutput createOutput(String name) {
    final ProcessorOutput output = new ProcessorOutputImpl(ZipProcessor.this, name) {

        String fileName = null;//w w w.j  a  va2  s . c  o  m
        int statusCode = -1;

        public void readImpl(PipelineContext context, XMLReceiver xmlReceiver) {
            try {
                // Create temporary zip file
                final FileItem fileItem = NetUtils.prepareFileItem(NetUtils.REQUEST_SCOPE, logger);
                fileItem.getOutputStream().close();
                final File temporaryZipFile = ((DiskFileItem) fileItem).getStoreLocation();
                temporaryZipFile.createNewFile();
                final ZipOutputStream zipOutputStream = new ZipOutputStream(
                        new FileOutputStream(temporaryZipFile));

                try {
                    // Read list of files and write to zip output stream as we go
                    readInputAsSAX(context, INPUT_DATA, new XMLReceiverAdapter() {

                        String name;
                        StringBuilder uri;

                        // Get the file name, store it
                        @Override
                        public void startElement(String namespaceURI, String localName, String qName,
                                Attributes atts) throws SAXException {
                            if ("file".equals(localName)) {
                                name = atts.getValue("name");
                                uri = new StringBuilder();
                            } else if ("files".equals(localName)) {
                                fileName = atts.getValue("filename");
                                String value = atts.getValue("status-code");
                                if (value != null) {
                                    statusCode = Integer.parseInt(value);
                                }
                            }
                        }

                        // Get the URI to the file, store it
                        @Override
                        public void characters(char ch[], int start, int length) throws SAXException {
                            if (uri != null)
                                uri.append(ch, start, length);
                        }

                        // Process file
                        @Override
                        public void endElement(String namespaceURI, String localName, String qName)
                                throws SAXException {
                            try {
                                if ("file".equals(localName)) {
                                    zipOutputStream.putNextEntry(new ZipEntry(name));
                                    final LocationData locationData = getLocationData();
                                    final String realPath;

                                    final URL fullURL = (locationData != null
                                            && locationData.getSystemID() != null)
                                                    ? URLFactory.createURL(locationData.getSystemID(),
                                                            uri.toString())
                                                    : URLFactory.createURL(uri.toString());

                                    if (fullURL.getProtocol().equals("oxf")) {
                                        // Get real path to resource path if possible
                                        realPath = ResourceManagerWrapper.instance()
                                                .getRealPath(fullURL.getFile());
                                        if (realPath == null)
                                            throw new OXFException(
                                                    "Zip processor is unable to obtain the real path of the file using the oxf: protocol for the base-directory property: "
                                                            + uri.toString());
                                    } else if (fullURL.getProtocol().equals("file")) {
                                        String host = fullURL.getHost();
                                        realPath = host + (host.length() > 0 ? ":" : "") + fullURL.getFile();
                                    } else {
                                        throw new OXFException(
                                                "Zip processor only supports the file: and oxf: protocols for the base-directory property: "
                                                        + uri.toString());
                                    }

                                    InputStream fileInputStream = new FileInputStream(new File(realPath));
                                    try {
                                        NetUtils.copyStream(fileInputStream, zipOutputStream);
                                    } finally {
                                        fileInputStream.close();
                                    }
                                }
                            } catch (IOException e) {
                                throw new OXFException(e);
                            }
                        }
                    });
                } finally {
                    zipOutputStream.close();
                }

                // Generate an Orbeon binary document with the content of the zip file
                FileInputStream zipInputStream = new FileInputStream(temporaryZipFile);
                try {
                    ProcessorUtils.readBinary(zipInputStream, xmlReceiver, "multipart/x-gzip", null, statusCode,
                            fileName);
                } finally {
                    zipInputStream.close();
                }
            } catch (FileNotFoundException e) {
                throw new OXFException(e);
            } catch (IOException e) {
                throw new OXFException(e);
            }
        }

        // We could assume that we cache if the input document hasn't changed. But this would be unsafe as some of
        // the files referenced from the input document could have changed. So to be on the safe side, and also
        // because the cases where caching could happen are rather rare, we just don't cache.
    };
    addOutput(name, output);
    return output;
}

From source file:org.orbeon.oxf.util.NetUtils.java

private static FileItem prepareFileItemFromInputStream(InputStream inputStream, int scope, Logger logger) {
    // Get FileItem
    final FileItem fileItem = prepareFileItem(scope, logger);
    // Write to file
    OutputStream os = null;//w ww  .  ja  v a2 s.  c o m
    try {
        os = fileItem.getOutputStream();
        copyStream(inputStream, os);
    } catch (IOException e) {
        throw new OXFException(e);
    } finally {
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
                throw new OXFException(e);
            }
        }
    }
    // Create file if it doesn't exist (necessary when the file size is 0)
    final File storeLocation = ((DiskFileItem) fileItem).getStoreLocation();
    try {
        storeLocation.createNewFile();
    } catch (IOException e) {
        throw new OXFException(e);
    }

    return fileItem;
}

From source file:org.sapia.soto.state.cocoon.util.CocoonFileUploadBase.java

/**
 * Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867 </a>
 * compliant <code>multipart/form-data</code> stream. If files are stored on
 * disk, the path is given by <code>getRepository()</code>.
 * /*ww w.j  a v a2s.  com*/
 * @param req
 *          The servlet request to be parsed.
 * 
 * @return A list of <code>FileItem</code> instances parsed from the
 *         request, in the order that they were transmitted.
 * 
 * @exception FileUploadException
 *              if there are problems reading/parsing the request or storing
 *              files.
 */
public List /* FileItem */ parseRequest(HttpRequest req) throws FileUploadException {
    if (null == req) {
        throw new NullPointerException("req parameter");
    }

    ArrayList items = new ArrayList();
    String contentType = req.getHeader(CONTENT_TYPE);

    if ((null == contentType) || (!contentType.startsWith(MULTIPART))) {
        throw new InvalidContentTypeException("the request doesn't contain a " + MULTIPART_FORM_DATA + " or "
                + MULTIPART_MIXED + " stream, content type header is " + contentType);
    }

    int requestSize = req.getContentLength();

    if (requestSize == -1) {
        throw new UnknownSizeException("the request was rejected because it's size is unknown");
    }

    if ((sizeMax >= 0) && (requestSize > sizeMax)) {
        throw new SizeLimitExceededException(
                "the request was rejected because " + "it's size exceeds allowed range");
    }

    try {
        int boundaryIndex = contentType.indexOf("boundary=");

        if (boundaryIndex < 0) {
            throw new FileUploadException(
                    "the request was rejected because " + "no multipart boundary was found");
        }

        byte[] boundary = contentType.substring(boundaryIndex + 9).getBytes();

        InputStream input = req.getInputStream();

        MultipartStream multi = new MultipartStream(input, boundary);
        multi.setHeaderEncoding(headerEncoding);

        boolean nextPart = multi.skipPreamble();

        while (nextPart) {
            Map headers = parseHeaders(multi.readHeaders());
            String fieldName = getFieldName(headers);

            if (fieldName != null) {
                String subContentType = getHeader(headers, CONTENT_TYPE);

                if ((subContentType != null) && subContentType.startsWith(MULTIPART_MIXED)) {
                    // Multiple files.
                    byte[] subBoundary = subContentType.substring(subContentType.indexOf("boundary=") + 9)
                            .getBytes();
                    multi.setBoundary(subBoundary);

                    boolean nextSubPart = multi.skipPreamble();

                    while (nextSubPart) {
                        headers = parseHeaders(multi.readHeaders());

                        if (getFileName(headers) != null) {
                            FileItem item = createItem(headers, false);
                            OutputStream os = item.getOutputStream();

                            try {
                                multi.readBodyData(os);
                            } finally {
                                os.close();
                            }

                            items.add(item);
                        } else {
                            // Ignore anything but files inside
                            // multipart/mixed.
                            multi.discardBodyData();
                        }

                        nextSubPart = multi.readBoundary();
                    }

                    multi.setBoundary(boundary);
                } else {
                    FileItem item = createItem(headers, getFileName(headers) == null);
                    OutputStream os = item.getOutputStream();

                    try {
                        multi.readBodyData(os);
                    } finally {
                        os.close();
                    }

                    items.add(item);
                }
            } else {
                // Skip this part.
                multi.discardBodyData();
            }

            nextPart = multi.readBoundary();
        }
    } catch (IOException e) {
        throw new FileUploadException(
                "Processing of " + MULTIPART_FORM_DATA + " request failed. " + e.getMessage());
    }

    return items;
}

From source file:play.data.parsing.ApacheMultipartParser.java

public Map<String, String[]> parse(InputStream body) {
    Map<String, String[]> result = new HashMap<String, String[]>();
    try {/*from w ww.  j  av a  2 s  .  co  m*/
        FileItemIteratorImpl iter = new FileItemIteratorImpl(body,
                Request.current().headers.get("content-type").value(), Request.current().encoding);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            FileItem fileItem = new AutoFileItem(item);
            try {
                Streams.copy(item.openStream(), fileItem.getOutputStream(), true);
            } catch (FileUploadIOException e) {
                throw (FileUploadException) e.getCause();
            } catch (IOException e) {
                throw new IOFileUploadException(
                        "Processing of " + MULTIPART_FORM_DATA + " request failed. " + e.getMessage(), e);
            }
            if (fileItem.isFormField()) {
                // must resolve encoding
                String _encoding = Request.current().encoding; // this is our default
                String _contentType = fileItem.getContentType();
                if (_contentType != null) {
                    HTTP.ContentTypeWithEncoding contentTypeEncoding = HTTP.parseContentType(_contentType);
                    if (contentTypeEncoding.encoding != null) {
                        _encoding = contentTypeEncoding.encoding;
                    }
                }

                putMapEntry(result, fileItem.getFieldName(), fileItem.getString(_encoding));
            } else {
                @SuppressWarnings("unchecked")
                List<Upload> uploads = (List<Upload>) Request.current().args.get("__UPLOADS");
                if (uploads == null) {
                    uploads = new ArrayList<Upload>();
                    Request.current().args.put("__UPLOADS", uploads);
                }
                try {
                    uploads.add(new FileUpload(fileItem));
                } catch (Exception e) {
                    // GAE does not support it, we try in memory
                    uploads.add(new MemoryUpload(fileItem));
                }
                putMapEntry(result, fileItem.getFieldName(), fileItem.getFieldName());
            }
        }
    } catch (FileUploadIOException e) {
        Logger.debug(e, "error");
        throw new IllegalStateException("Error when handling upload", e);
    } catch (IOException e) {
        Logger.debug(e, "error");
        throw new IllegalStateException("Error when handling upload", e);
    } catch (FileUploadException e) {
        Logger.debug(e, "error");
        throw new IllegalStateException("Error when handling upload", e);
    } catch (Exception e) {
        Logger.debug(e, "error");
        throw new UnexpectedException(e);
    }
    return result;
}

From source file:zutil.jee.upload.AjaxFileUpload.java

@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    FileUploadListener listener = new FileUploadListener();
    try {//w ww. j  a  v  a  2  s  .  c  o m
        // Initiate list and HashMap that will contain the data
        HashMap<String, String> fields = new HashMap<String, String>();
        ArrayList<FileItem> files = new ArrayList<FileItem>();

        // Add the listener to the session
        HttpSession session = request.getSession();
        LinkedList<FileUploadListener> list = (LinkedList<FileUploadListener>) session
                .getAttribute(SESSION_FILEUPLOAD_LISTENER);
        if (list == null) {
            list = new LinkedList<FileUploadListener>();
            session.setAttribute(SESSION_FILEUPLOAD_LISTENER, list);
        }
        list.add(listener);

        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();
        if (TEMPFILE_PATH != null)
            factory.setRepository(TEMPFILE_PATH);
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setProgressListener(listener);
        // Set overall request size constraint
        //upload.setSizeMax(yourMaxRequestSize);

        // Parse the request
        FileItemIterator it = upload.getItemIterator(request);
        while (it.hasNext()) {
            FileItemStream item = it.next();
            // Is the file type allowed?
            if (!item.isFormField()
                    && !ALLOWED_EXTENSIONS.contains(FileUtil.getFileExtension(item.getName()).toLowerCase())) {
                String msg = "Filetype '" + FileUtil.getFileExtension(item.getName()) + "' is not allowed!";
                logger.warning(msg);
                listener.setStatus(Status.Error);
                listener.setFileName(item.getName());
                listener.setMessage(msg);
                return;
            }
            listener.setFileName(item.getName());
            FileItem fileItem = factory.createItem(item.getFieldName(), item.getContentType(),
                    item.isFormField(), item.getName());
            // Read the file data
            Streams.copy(item.openStream(), fileItem.getOutputStream(), true);
            if (fileItem instanceof FileItemHeadersSupport) {
                final FileItemHeaders fih = item.getHeaders();
                ((FileItemHeadersSupport) fileItem).setHeaders(fih);
            }

            //Handle the item
            if (fileItem.isFormField()) {
                fields.put(fileItem.getFieldName(), fileItem.getString());
            } else {
                files.add(fileItem);
                logger.info("Recieved file: " + fileItem.getName() + " ("
                        + StringUtil.formatByteSizeToString(fileItem.getSize()) + ")");
            }
        }
        // Process the upload
        listener.setStatus(Status.Processing);
        doUpload(request, response, fields, files);
        // Done
        listener.setStatus(Status.Done);
    } catch (Exception e) {
        logger.log(Level.SEVERE, null, e);
        listener.setStatus(Status.Error);
        listener.setFileName("");
        listener.setMessage(e.getMessage());
    }
}