Example usage for org.apache.commons.fileupload FileUploadBase isMultipartContent

List of usage examples for org.apache.commons.fileupload FileUploadBase isMultipartContent

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileUploadBase isMultipartContent.

Prototype

public static final boolean isMultipartContent(HttpServletRequest req) 

Source Link

Document

Utility method that determines whether the request contains multipart content.

Usage

From source file:com.yanzhenjie.andserver.upload.HttpFileUpload.java

public static final boolean isMultipartContentWithPost(HttpRequest request) {
    String method = request.getRequestLine().getMethod();
    return "POST".equalsIgnoreCase(method) && (request instanceof HttpEntityEnclosingRequest
            && FileUploadBase.isMultipartContent(new HttpUploadContext((HttpEntityEnclosingRequest) request)));
}

From source file:com.yanzhenjie.andserver.upload.HttpFileUpload.java

public static final boolean isMultipartContent(HttpRequest request) {
    return (request instanceof HttpEntityEnclosingRequest
            && FileUploadBase.isMultipartContent(new HttpUploadContext((HttpEntityEnclosingRequest) request)));
}

From source file:com.exedio.copernica.Form.java

@SuppressWarnings("deprecation") // TODO use new way of fileupload
public Form(final HttpServletRequest request) {
    this.request = request;

    if (FileUploadBase.isMultipartContent(request)) {
        final org.apache.commons.fileupload.DiskFileUpload upload = new org.apache.commons.fileupload.DiskFileUpload();
        final int maxSize = 100 * 1024; // TODO: make this configurable
        upload.setSizeThreshold(maxSize); // TODO: always save to disk
        upload.setSizeMax(maxSize);/* w w  w  . ja v  a 2  s .co m*/
        //upload.setRepositoryPath("");
        multipartContentParameters = new HashMap<String, Object>();
        try {
            for (Iterator<?> i = upload.parseRequest(request).iterator(); i.hasNext();) {
                final FileItem item = (FileItem) i.next();
                if (item.isFormField()) {
                    final String name = item.getFieldName();
                    final String value = item.getString();
                    multipartContentParameters.put(name, value);
                } else {
                    final String name = item.getFieldName();
                    multipartContentParameters.put(name, item);
                }
            }
        } catch (FileUploadException e) {
            throw new RuntimeException(e);
        }
    } else {
        multipartContentParameters = null;
    }
}

From source file:info.magnolia.cms.filters.CommonsFileUploadMultipartRequestFilter.java

/**
 * Determine if the request has multipart content and if so parse it into a <code>MultipartForm</code> and store
 * it as a request attribute./*from w  w  w . j  a va 2  s  .  com*/
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse,
 * javax.servlet.FilterChain)
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (request instanceof HttpServletRequest) {
        boolean isMultipartContent = FileUploadBase.isMultipartContent((HttpServletRequest) request);
        if (isMultipartContent) {
            try {
                parseRequest((HttpServletRequest) request);
            } catch (IOException e) {
                throw e;
            } catch (Exception e) {
                throw new ServletException(e);
            }
        }
    }

    chain.doFilter(request, response);
}

From source file:ccc.plugins.multipart.apache.MultipartForm.java

/**
 * Parse an HTTP request, extracting the file items.
 *
 * @param context The JAXRS context to parse.
 *
 * @return A list of file items./*from w  w  w .  j a v a 2  s. c  o m*/
 */
@SuppressWarnings("unchecked")
private static List<FileItem> parseFileItems(final JaxrsRequestContext context) {

    DBC.require().notNull(context);

    // Check that we have a file upload request
    final boolean isMultipart = FileUploadBase.isMultipartContent(context);
    if (!isMultipart) {
        throw new RuntimeException("Not a multipart.");
    }

    // Create a factory for disk-based file items
    final DiskFileItemFactory factory = new DiskFileItemFactory();

    // Set factory constraints
    factory.setSizeThreshold(maxInMemorySize());

    // Create a new file upload handler
    final FileUpload upload = new FileUpload(factory);

    // Set overall request size constraint
    upload.setFileSizeMax(maxFileSize());

    try {
        return upload.parseRequest(context);
    } catch (final FileSizeLimitExceededException e) {
        throw handleTooBig(e, e.getPermittedSize());
    } catch (final SizeLimitExceededException e) {
        throw handleTooBig(e, e.getPermittedSize());
    } catch (final FileUploadException e) {
        throw new RuntimeException("Failed to parse multipart request.", e);
    }
}

From source file:net.jforum.core.support.vraptor.DefaultLogicLocator.java

@SuppressWarnings({ "deprecation", "unchecked" })
private void handleMultipartRequest(VRaptorServletRequest servletRequest) {
    if (!FileUploadBase.isMultipartContent(servletRequest)) {
        return;/*from   ww  w. java  2 s. c o  m*/
    }

    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory(4096 * 16, this.temporaryDirectory);

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    List<FileItem> fileItems;

    // assume we know there are two files. The first file is a small
    // text file, the second is unknown and is written to a file on
    // the server
    try {
        fileItems = upload.parseRequest(servletRequest);
    } catch (FileUploadException e) {
        logger.warn("There was some problem parsing this multipart request, or someone is not sending a "
                + "RFC1867 compatible multipart request.", e);
        return;
    }

    for (FileItem item : fileItems) {
        if (item.isFormField()) {
            servletRequest.addParameterValue(item.getFieldName(), item.getString());
        } else {
            if (!item.getName().trim().equals("")) {
                try {
                    File file = File.createTempFile("vraptor.", ".upload");
                    item.write(file);

                    UploadedFileInformation fileInformation = new BasicUploadedFileInformation(file,
                            item.getName(), item.getContentType());

                    this.registeUploadedFile(servletRequest, item.getFieldName(), fileInformation);
                } catch (Exception e) {
                    logger.error("Nasty uploaded file " + item.getName(), e);
                }
            } else {
                logger.debug("A file field was empy: " + item.getFieldName());
            }
        }
    }
}

From source file:eu.webtoolkit.jwt.servlet.WebRequest.java

@SuppressWarnings({ "unchecked", "deprecation" })
private void parse(final ProgressListener progressUpdate) throws IOException {
    if (FileUploadBase.isMultipartContent(this)) {
        try {/*  www  .  j a  v  a  2 s  .c  o m*/
            // Create a factory for disk-based file items
            DiskFileItemFactory factory = new DiskFileItemFactory();

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);

            if (progressUpdate != null) {
                upload.setProgressListener(new org.apache.commons.fileupload.ProgressListener() {
                    public void update(long pBytesRead, long pContentLength, int pItems) {
                        progressUpdate.update(WebRequest.this, pBytesRead, pContentLength);
                    }
                });
            }

            // Parse the request
            List items = upload.parseRequest(this);

            parseParameters();

            Iterator itr = items.iterator();

            FileItem fi;
            File f = null;
            while (itr.hasNext()) {
                fi = (FileItem) itr.next();

                // Check if not form field so as to only handle the file inputs
                // else condition handles the submit button input
                if (!fi.isFormField()) {
                    try {
                        f = File.createTempFile("jwt", "jwt");
                        fi.write(f);
                        fi.delete();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    List<UploadedFile> files = files_.get(fi.getFieldName());
                    if (files == null) {
                        files = new ArrayList<UploadedFile>();
                        files_.put(fi.getFieldName(), files);
                    }
                    files.add(new UploadedFile(f.getAbsolutePath(), fi.getName(), fi.getContentType()));
                } else {
                    String[] v = parameters_.get(fi.getFieldName());
                    if (v == null)
                        v = new String[1];
                    else {
                        String[] newv = new String[v.length + 1];
                        for (int i = 0; i < v.length; ++i)
                            newv[i] = v[i];
                        v = newv;
                    }
                    v[v.length - 1] = fi.getString();
                    parameters_.put(fi.getFieldName(), v);
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
    } else
        parseParameters();
}

From source file:com.enonic.cms.web.portal.services.ServicesProcessorBase.java

private ExtendedMap parseForm(HttpServletRequest request) {
    if (FileUploadBase.isMultipartContent(new ServletRequestContext(request))) {
        return parseMultiPartRequest(request);
    } else {//from   ww w. j ava2 s.c om
        return parseSimpleRequest(request);
    }
}

From source file:dk.kontentsu.api.exposure.ItemExposure.java

private static boolean isMultipartContent(final HttpServletRequest request) {
    return FileUploadBase.isMultipartContent(new ServletRequestContext(request));
}

From source file:org.apache.felix.webconsole.WebConsoleUtil.java

/**
 * An utility method, that is used to filter out simple parameter from file
 * parameter when multipart transfer encoding is used.
 *
 * This method processes the request and sets a request attribute
 * {@link AbstractWebConsolePlugin#ATTR_FILEUPLOAD}. The attribute value is a {@link Map}
 * where the key is a String specifying the field name and the value
 * is a {@link org.apache.commons.fileupload.FileItem}.
 *
 * @param request the HTTP request coming from the user
 * @param name the name of the parameter
 * @return if not multipart transfer encoding is used - the value is the
 *  parameter value or <code>null</code> if not set. If multipart is used,
 *  and the specified parameter is field - then the value of the parameter
 *  is returned./*  w  w  w  .j  a v a  2s. c  om*/
 */
public static final String getParameter(HttpServletRequest request, String name) {
    // just get the parameter if not a multipart/form-data POST
    if (!FileUploadBase.isMultipartContent(new ServletRequestContext(request))) {
        return request.getParameter(name);
    }

    // check, whether we already have the parameters
    Map params = (Map) request.getAttribute(AbstractWebConsolePlugin.ATTR_FILEUPLOAD);
    if (params == null) {
        // parameters not read yet, read now
        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(256000);

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(-1);

        // Parse the request
        params = new HashMap();
        try {
            List items = upload.parseRequest(request);
            for (Iterator fiter = items.iterator(); fiter.hasNext();) {
                FileItem fi = (FileItem) fiter.next();
                FileItem[] current = (FileItem[]) params.get(fi.getFieldName());
                if (current == null) {
                    current = new FileItem[] { fi };
                } else {
                    FileItem[] newCurrent = new FileItem[current.length + 1];
                    System.arraycopy(current, 0, newCurrent, 0, current.length);
                    newCurrent[current.length] = fi;
                    current = newCurrent;
                }
                params.put(fi.getFieldName(), current);
            }
        } catch (FileUploadException fue) {
            // TODO: log
        }
        request.setAttribute(AbstractWebConsolePlugin.ATTR_FILEUPLOAD, params);
    }

    FileItem[] param = (FileItem[]) params.get(name);
    if (param != null) {
        for (int i = 0; i < param.length; i++) {
            if (param[i].isFormField()) {
                return param[i].getString();
            }
        }
    }

    // no valid string parameter, fail
    return null;
}