Example usage for org.apache.commons.fileupload.disk DiskFileItemFactory setSizeThreshold

List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory setSizeThreshold

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.disk DiskFileItemFactory setSizeThreshold.

Prototype

public void setSizeThreshold(int sizeThreshold) 

Source Link

Document

Sets the size threshold beyond which files are written directly to disk.

Usage

From source file:org.opensubsystems.core.util.servlet.WebParamUtils.java

/**
 * Parse multipart request and separate regular parameters and files. The
 * files names are also stored as values of the parameters that are used to 
 * upload them./*w  ww . j a  va2 s. co  m*/
 * 
 * @param strLogPrefix - log prefix used for all log output to tie together
 *                       the same invocations
 * @param request - request to get parameter from
 * @return TwoElementStruct<Map<String, String>, Map<String, FileItem>> - the
 *                  first element is map of parameter names and their values. 
 *                  For uploaded files the files names are also stored here as 
 *                  values of the parameters that are used to upload them.
 *                  If there is only one value of the parameter then the value
 *                  is stored directly as String. If there are multiple values
 *                  then the values are stored as List<String>.
 *                  The second element is map of parameter names and the files
 *                  that are uploaded as these parameters.
 * @throws FileUploadException - an error has occurred
 */
public static TwoElementStruct<Map<String, Object>, Map<String, FileItem>> parseMultipartRequest(
        String strLogPrefix, HttpServletRequest request) throws FileUploadException {
    if (GlobalConstants.ERROR_CHECKING) {
        assert ServletFileUpload.isMultipartContent(request) : "Specified request is not multipart";
    }

    TwoElementStruct<Map<String, Object>, Map<String, FileItem>> returnValue;
    FileCleaningTracker fileCleaningTracker;
    String strTempDir;
    DiskFileItemFactory factory;
    Properties prpSettings;
    int iMaxInMemorySize;
    int iMaxSize;
    ServletFileUpload upload;
    List<FileItem> items;

    // TODO: Improve: Consider calling 
    // FileUtils.createTemporarySubdirectory
    // as done in legacy Formature.DocumentTemplateServlet.getFormToProcess
    // to store the temporary files per session and request
    strTempDir = FileUtils.getTemporaryDirectory();

    prpSettings = Config.getInstance().getProperties();
    iMaxInMemorySize = PropertyUtils.getIntPropertyInRange(prpSettings, REQUEST_UPLOAD_MEMORY_THRESHOLD,
            REQUEST_UPLOAD_MEMORY_THRESHOLD_DEFAULT, "Maximal size of uploaded file that is kept in memory", 1, // 0 is allowed 
            Integer.MAX_VALUE);
    iMaxSize = PropertyUtils.getIntPropertyInRange(prpSettings, REQUEST_UPLOAD_MAX_SIZE,
            REQUEST_UPLOAD_MAX_SIZE_DEFAULT, "Maximal size of uploaded file", 1, // 0 is allowed 
            Integer.MAX_VALUE);

    fileCleaningTracker = FileCleanerCleanup.getFileCleaningTracker(request.getServletContext());

    // Create a factory for disk-based file items
    factory = new DiskFileItemFactory();
    factory.setFileCleaningTracker(fileCleaningTracker);
    // Set factory constraints
    factory.setSizeThreshold(iMaxInMemorySize);
    factory.setRepository(new File(strTempDir));

    // Create a new file upload handler
    upload = new ServletFileUpload(factory);
    // Set overall request size constraint
    upload.setSizeMax(iMaxSize);

    // Parse the request
    items = upload.parseRequest(request);
    if ((items != null) && (!items.isEmpty())) {
        Map mpParams;
        Map mpFiles;
        String strParamName;
        String strValue;
        Object temp;
        List<String> lstValues;

        mpParams = new HashMap(items.size());
        mpFiles = new HashMap();

        returnValue = new TwoElementStruct(mpParams, mpFiles);
        for (FileItem item : items) {
            strParamName = item.getFieldName();
            if (item.isFormField()) {
                strValue = item.getString();
            } else {
                strValue = item.getName();
                mpFiles.put(strParamName, item);
            }

            temp = mpParams.put(strParamName, strValue);
            if (temp != null) {
                // There was already an value so convert it to list of values
                if (temp instanceof String) {
                    // There are currently exactly two values
                    lstValues = new ArrayList<>();
                    lstValues.add((String) temp);
                    mpParams.put(strParamName, lstValues);
                } else {
                    // There are currently more than two values
                    lstValues = (List<String>) temp;
                }
                lstValues.add(strValue);
            }
        }
    } else {
        returnValue = new TwoElementStruct(Collections.emptyMap(), Collections.emptyMap());
    }

    return returnValue;
}

From source file:org.origin.common.servlet.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//from w w  w . ja  va2 s  .c  om
 *            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.
 */
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(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);
        // See https://issues.apache.org/jira/browse/FELIX-4660
        final Object repo = request.getAttribute(ATTR_FILEUPLOAD_REPO);
        if (repo instanceof File) {
            factory.setRepository((File) repo);
        }

        // 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(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;
}

From source file:org.ow2.proactive_grid_cloud_portal.common.server.CredentialsServlet.java

private void login(HttpServletRequest request, HttpServletResponse response) {
    response.setContentType("text/html");

    try {//from w w w.j a v  a  2s. c  o  m
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(4096);
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(1000000);

        List<?> fileItems = upload.parseRequest(request);
        Iterator<?> i = fileItems.iterator();

        String user = "";
        String pass = "";
        String sshKey = "";

        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();

            if (fi.isFormField()) {
                String name = fi.getFieldName();
                String value = fi.getString();

                if (name.equals("username")) {
                    user = value;
                } else if (name.equals("password")) {
                    pass = value;
                }
            } else {
                String field = fi.getFieldName();
                byte[] bytes = IOUtils.toByteArray(fi.getInputStream());
                if (field.equals("sshkey")) {
                    sshKey = new String(bytes);
                }
            }
            fi.delete();
        }

        String responseS = Service.get().createCredentials(user, pass, sshKey);
        response.setHeader("Content-disposition", "attachment; filename=" + user + "_cred.txt");
        response.setHeader("Location", "" + user + ".cred.txt");
        response.getWriter().write(responseS);

    } catch (Throwable t) {
        try {
            response.getWriter().write(t.getMessage());
        } catch (IOException e1) {
            LOGGER.warn("Failed to return login error to client, error was:" + t.getMessage(), e1);
        }
    }
}

From source file:org.ow2.proactive_grid_cloud_portal.common.server.LoginServlet.java

private void login(HttpServletRequest request, HttpServletResponse response) {
    response.setContentType("text/html");
    File cred = null;//w w  w  .  ja va 2 s  .c om
    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(4096);
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(1000000);

        List<?> fileItems = upload.parseRequest(request);
        Iterator<?> i = fileItems.iterator();

        String user = "";
        String pass = "";
        String sshKey = "";

        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();

            if (fi.isFormField()) {
                String name = fi.getFieldName();
                String value = fi.getString();

                if (name.equals("username")) {
                    user = value;
                } else if (name.equals("password")) {
                    pass = value;
                }
            } else {
                String field = fi.getFieldName();

                byte[] bytes = IOUtils.toByteArray(fi.getInputStream());

                if (field.equals("credential")) {
                    cred = File.createTempFile("credential", null);
                    cred.deleteOnExit();
                    fi.write(cred);
                } else if (field.equals("sshkey")) {
                    sshKey = new String(bytes);
                }
            }

            fi.delete();
        }

        String responseS = Service.get().login(user, pass, cred, sshKey);
        String s = "{ \"sessionId\" : \"" + responseS + "\" }";
        response.getWriter().write(SafeHtmlUtils.htmlEscape(s));
    } catch (Throwable t) {
        try {
            response.getWriter().write(SafeHtmlUtils.htmlEscape(t.getMessage()));
        } catch (IOException e1) {
            LOGGER.warn("Failed to return login error to client, error was:" + t.getMessage(), e1);
        }
    } finally {
        if (cred != null)
            cred.delete();
    }
}

From source file:org.ow2.proactive_grid_cloud_portal.rm.server.NSCreationServlet.java

private void createNs(HttpServletRequest request, HttpServletResponse response) {

    String sessionId = "";
    String callbackName = "";
    String nsName = "";
    String infra = "";
    String policy = "";

    ArrayList<String> infraParams = new ArrayList<>();
    ArrayList<String> infraFileParams = new ArrayList<>();
    ArrayList<String> policyParams = new ArrayList<>();
    ArrayList<String> policyFileParams = new ArrayList<>();

    boolean readingInfraParams = false;
    boolean readingPolicyParams = false;

    try {/*from w  ww  . j a v a 2  s .com*/
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(4096);
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(MAX_UPLOAD_SIZE);

        List<?> fileItems = upload.parseRequest(request);
        Iterator<?> i = fileItems.iterator();
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            String fieldName = fi.getFieldName();
            if (fi.isFormField()) {
                if (fieldName.equals("sessionId")) {
                    sessionId = fi.getString();
                } else if (fieldName.equals("nsCallback")) {
                    callbackName = fi.getString();
                } else if (fieldName.equals("nsName")) {
                    nsName = fi.getString();
                } else if (fieldName.equals("infra")) {
                    infra = fi.getString();
                    readingInfraParams = true;
                } else if (fieldName.equals("policy")) {
                    policy = fi.getString();
                    readingPolicyParams = true;
                    readingInfraParams = false;
                } else if (readingInfraParams) {
                    infraParams.add(fi.getString());
                } else if (readingPolicyParams) {
                    policyParams.add(fi.getString());
                } else {
                    LOGGER.warn("Unexpected param " + fieldName);
                }
            } else {
                if (readingInfraParams) {
                    byte[] bytes = IOUtils.toByteArray(fi.getInputStream());
                    infraFileParams.add(new String(bytes));
                } else if (readingPolicyParams) {
                    byte[] bytes = IOUtils.toByteArray(fi.getInputStream());
                    policyFileParams.add(new String(bytes));
                } else {
                    LOGGER.warn("Unexpected param " + fieldName);
                }
            }
        }
        String failFast = null;
        if (nsName.length() == 0) {
            failFast = "You need to pick a name for the new Node Source";
        } else if (policy.length() == 0 || policy.equals("undefined")) {
            failFast = "No Policy selected";
        } else if (infra.length() == 0 || infra.equals("undefined")) {
            failFast = "No Infrastructure selected";
        }

        if (failFast != null) {
            throw new RestServerException(failFast);
        }

        String jsonResult = ((RMServiceImpl) RMServiceImpl.get()).createNodeSource(sessionId, nsName, infra,
                toArray(infraParams), toArray(infraFileParams), policy, toArray(policyParams),
                toArray(policyFileParams));

        if (jsonResult.equals("true")) {
            jsonResult = createNonEscapedSimpleJsonPair("result", "true");
        }

        write(response, createJavascriptPayload(callbackName, jsonResult));
    } catch (Throwable t) {
        write(response, createJavascriptPayload(callbackName,
                createEscapedSimpleJsonPair("errorMessage", t.getMessage())));
    }
}

From source file:org.ow2.proactive_grid_cloud_portal.rm.server.ServletRequestTransformer.java

@SuppressWarnings("unchecked")
public List<FileItem> getFormItems(HttpServletRequest request) throws FileUploadException {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(FILE_ITEM_THRESHOLD_SIZE);
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(MAX_FILE_UPLOAD_SIZE);
    return (List<FileItem>) upload.parseRequest(request);
}

From source file:org.ow2.proactive_grid_cloud_portal.scheduler.server.FlatJobServlet.java

private void upload(HttpServletRequest request, HttpServletResponse response) {
    response.setContentType("text/html");

    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(4096);
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(1000000);/*w  w  w  .j  a v a  2 s .  c  o  m*/
    String callbackName = null;

    try {
        List<?> fileItems = upload.parseRequest(request);
        Iterator<?> i = fileItems.iterator();

        String commandFile = null;
        String name = null;
        String selectionScript = null;
        String selectionScriptExtension = null;
        String sessionId = null;

        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();

            if (fi.isFormField()) {
                if (fi.getFieldName().equals("jobName")) {
                    name = fi.getString();
                    if (name.trim().length() == 0)
                        name = null;
                } else if (fi.getFieldName().equals("sessionId")) {
                    sessionId = fi.getString();
                } else if (fi.getFieldName().equals("flatCallback")) {
                    callbackName = fi.getString();
                }
            } else {
                if (fi.getFieldName().equals("commandFile")) {
                    commandFile = IOUtils.toString(fi.getInputStream());
                    if (commandFile.trim().length() == 0)
                        commandFile = null;
                } else if (fi.getFieldName().equals("selectionScript")) {
                    if (fi.getName().indexOf('.') == -1) {
                        selectionScriptExtension = "js";
                    } else {
                        selectionScriptExtension = fi.getName().substring(fi.getName().lastIndexOf('.') + 1);
                    }
                    selectionScript = IOUtils.toString(fi.getInputStream());
                    if (selectionScript.trim().length() == 0)
                        selectionScript = null;
                }
            }
        }

        String ret;
        if (commandFile == null) {
            ret = "{ \"errorMessage\" : \"Missing parameter: command file\" }";
        } else if (sessionId == null) {
            ret = "{ \"errorMessage\" : \"Missing parameter: sessionId\" }";
        } else if (name == null) {
            ret = "{ \"errorMessage\" : \"Missing parameter: job name\" }";
        } else {
            ret = ((SchedulerServiceImpl) SchedulerServiceImpl.get()).submitFlatJob(sessionId, commandFile,
                    name, selectionScript, selectionScriptExtension);
        }
        /* writing the callback name in as an inlined script,
         * so that the browser, upon receiving it, will evaluate
         * the JS and call the function */
        response.getWriter().write("<script type='text/javascript'>");
        response.getWriter().write("window.top." + callbackName + "(" + ret + ");");
        response.getWriter().write("</script>");

    } catch (RestServerException e) {
        try {
            response.getWriter().write("<script type='text/javascript'>");
            response.getWriter().write("window.top." + callbackName + " (" + e.getMessage() + ")");
            response.getWriter().write("</script>");
        } catch (Throwable e1) {
            LOGGER.warn("Failed to write script back to client", e);
        }
    } catch (Exception e) {
        try {
            String tw = "<script type='text/javascript'>";
            tw += "window.top." + callbackName + "({ \"errorMessage\" : \"" + e.getMessage() + "\" });";
            tw += "</script>";
            response.getWriter().write(tw);
        } catch (IOException e1) {
            LOGGER.warn("Failed to write script back to client", e);
        }
    }
}

From source file:org.ow2.proactive_grid_cloud_portal.scheduler.server.UploadServlet.java

private void upload(HttpServletRequest request, HttpServletResponse response) {
    response.setContentType("text/html");
    File job = null;// w w w . ja va 2s  .co  m

    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(4096);
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(1000000);

        List<?> fileItems = upload.parseRequest(request);
        Iterator<?> i = fileItems.iterator();

        String sessionId = null;
        boolean edit = false;

        /*
         * * edit=0, simply submit the job descriptor * edit=1, open the descriptor and return
         * it as a string
         */

        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();

            if (fi.isFormField()) {
                if (fi.getFieldName().equals("sessionId")) {
                    sessionId = fi.getString();
                } else if (fi.getFieldName().equals("edit")) {
                    if (fi.getString().equals("1")) {
                        edit = true;
                    } else {
                        edit = false;
                    }
                }
            } else {
                job = File.createTempFile("job_upload", ".xml");
                fi.write(job);
            }

            fi.delete();
        }

        boolean isJar = isJarFile(job);

        if (!isJar) {
            // this _loosely_ checks that the file we got is an XML file 
            try {
                DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
                Document doc = docBuilder.parse(job);

                if (edit) {
                    // don't go on with edition if there are no variables
                    if (doc.getElementsByTagName("variables").getLength() < 1
                            || doc.getElementsByTagName("variable").getLength() < 1) {
                        response.getWriter().write("This job descriptor contains no variable definition.<br>"
                                + "Uncheck <strong>Edit variables</strong> or submit another descriptor.");
                        return;
                    }
                }
            } catch (Throwable e) {
                response.getWriter().write("Job descriptor must be valid XML<br>" + e.getMessage());
                return;
            }
        }

        if (edit && !isJar) {
            String ret = IOUtils.toString(new FileInputStream(job), "UTF-8");
            response.getWriter().write("{ \"jobEdit\" : \"" + Base64Utils.toBase64(ret.getBytes()) + "\" }");
        } else {
            String responseS = ((SchedulerServiceImpl) Service.get()).submitXMLFile(sessionId, job);
            if (responseS == null || responseS.length() == 0) {
                response.getWriter().write("Job submission returned without a value!");
            } else {
                response.getWriter().write(responseS);
            }
        }

    } catch (Exception e) {
        try {
            String msg = e.getMessage().replace("<", "&lt;").replace(">", "&gt;");
            response.getWriter().write(msg);
        } catch (IOException ignored) {
        }
    } finally {
        if (job != null)
            job.delete();
    }

}

From source file:org.owasp.webgoat.lessons.MaliciousFileExecution.java

/**
 * Constructor for the DatabaseFieldScreen object
 * //from  w w  w . j a va 2s. co m
 * @param s
 *                Description of the Parameter
 */
public void handleRequest(WebSession s) {

    if (uploads_and_target_parent_directory == null) {
        fill_uploads_and_target_parent_directory(s);
    }

    try {
        if (ServletFileUpload.isMultipartContent(s.getRequest())) {
            // multipart request - we have the file upload

            //          Create a factory for disk-based file items
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(500000); // files over 500k will be written to disk temporarily.  
            // files under that size will be stored in memory until written to disk by the request handler code below

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

            //          Parse the request
            List /* FileItem */ items = upload.parseRequest(s.getRequest());

            //          Process the uploaded items
            java.util.Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();

                if (item.isFormField()) {

                    // ignore regular form fields

                } else {

                    // not a form field, must be a file upload
                    if (item.getName().contains("/") || item.getName().contains("\\")) {
                        System.out.println(
                                "Uploaded file contains a / or \\ (i.e. attempted directory traversal).  Not storing file.");
                        // TODO - is there a way to show an error to the user here?

                        s.setMessage("Directory traversal not allowed.  Nice try though.");

                    } else {

                        // write file to disk with original name in uploads directory
                        String uploaded_file_path = uploads_and_target_parent_directory + UPLOADS_RELATIVE_PATH
                                + java.io.File.separator + item.getName();
                        File uploadedFile = new File(uploaded_file_path);
                        item.write(uploadedFile);
                        System.out.println("Stored file:\n" + uploaded_file_path);

                        // add url to database table
                        Connection connection = DatabaseUtilities.getConnection(s);

                        Statement statement = connection.createStatement();

                        // attempt an update
                        String updateData1 = "UPDATE mfe_images SET image_relative_url='"
                                + UPLOADS_RELATIVE_PATH + "/" + item.getName() + "' WHERE user_name = '"
                                + s.getUserName() + "';";

                        System.out.println("Updating row:\n" + updateData1);
                        if (statement.executeUpdate(updateData1) == 0) {

                            // update failed, we need to add a row
                            String insertData1 = "INSERT INTO mfe_images VALUES ('" + s.getUserName() + "','"
                                    + UPLOADS_RELATIVE_PATH + "/" + item.getName() + "')";

                            System.out.println("Inserting row:\n" + insertData1);
                            statement.executeUpdate(insertData1);

                        }
                    }

                }
            }

        }
        // now handle normally (if it was a multipart request or now)

        //super.handleRequest(s);

        // needed to cut and paste and edit rather than calling super 
        // here so that we could set the encoding type to multipart form data
        // call createContent first so messages will go somewhere

        Form form = new Form(getFormAction(), Form.POST).setName("form").setEncType("multipart/form-data");

        form.addElement(createContent(s));

        setContent(form);
    } catch (Exception e) {
        System.out.println("Exception caught: " + e);
        e.printStackTrace(System.out);
    }
}

From source file:org.owasp.webgoat.lessons.ZipBomb.java

public void handleRequest(WebSession s) {
    File tmpDir = (File) s.getRequest().getServletContext().getAttribute("javax.servlet.context.tempdir");

    try {// w  w  w  . ja va  2 s .c  o m
        if (ServletFileUpload.isMultipartContent(s.getRequest())) {

            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(500000);

            ServletFileUpload upload = new ServletFileUpload(factory);

            List /* FileItem */ items = upload.parseRequest(s.getRequest());

            java.util.Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();

                if (!item.isFormField()) {

                    File uploadedFile = new File(tmpDir, item.getName());

                    if (item.getSize() < 2000 * 1024) {
                        if (item.getName().endsWith(".zip")) {
                            item.write(uploadedFile);

                            long total = unzippedSize(uploadedFile);
                            s.setMessage("File uploaded");
                            if (total > 20 * 1024 * 1024) {
                                s.add(ZIP_DOS, "success");
                                System.out.println("success");
                                makeMessages(s);
                            } else {
                                s.setMessage("I still have plenty of free storage on the server...");
                            }

                        } else {
                            s.setMessage("Only ZIP files are accepted");
                        }
                    } else {
                        s.setMessage("Only up to 2 MB files are accepted");
                    }
                }
            }

        }
        Form form = new Form(getFormAction(), Form.POST).setName("form").setEncType("multipart/form-data");

        form.addElement(createContent(s));

        setContent(form);

    } catch (Exception e) {
        e.printStackTrace(System.out);
    }
}