Example usage for org.apache.commons.fileupload.servlet ServletFileUpload setSizeMax

List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload setSizeMax

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.servlet ServletFileUpload setSizeMax.

Prototype

public void setSizeMax(long sizeMax) 

Source Link

Document

Sets the maximum allowed upload size.

Usage

From source file:kotys.monika.MenuCreatorJSP.LoadData.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request// w ww.j  a v a  2 s.  co  m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Check that we have a file upload request
    request.setCharacterEncoding("UTF-8");
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    ArrayList<String> files = new ArrayList<String>();

    if (!isMultipart) {
        return;
    }

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

    // Sets the size threshold beyond which files are written directly to
    // disk.
    factory.setSizeThreshold(MAX_MEMORY_SIZE);

    // Sets the directory used to temporarily store files that are larger
    // than the configured size threshold. We use temporary directory for
    // java
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    // constructs the folder where uploaded file will be stored
    String uploadFolder = getServletContext().getRealPath("") + File.separator + DATA_DIRECTORY;

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

    // Set overall request size constraint
    upload.setSizeMax(MAX_REQUEST_SIZE);

    try {
        // Parse the request
        List items = upload.parseRequest(request);
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (!item.isFormField()) {
                String fileName = new File(item.getName()).getName();
                String filePath = uploadFolder + File.separator + fileName;
                File uploadedFile = new File(filePath);
                System.out.println(filePath);
                // saves the file to upload directory
                item.write(uploadedFile);
                files.add(filePath);
            }
        }

        // displays done.jsp page after upload finished
        request.getSession().setAttribute("uploadedFiles", files);
        processRequest(request, response);

    } catch (FileUploadException ex) {
        throw new ServletException(ex);
    } catch (Exception ex) {
        Logger.getLogger(LoadData.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.skin.generator.action.UploadTestAction.java

/**
 * @param request/* w w  w  . j a v  a 2  s. c  o  m*/
 * @return Map<String, Object>
 * @throws Exception
 */
public Map<String, Object> parse(HttpServletRequest request) throws Exception {
    String repository = System.getProperty("java.io.tmpdir");
    int maxFileSize = 1024 * 1024 * 1024;
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setRepository(new File(repository));
    factory.setSizeThreshold(1024 * 1024);
    ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
    servletFileUpload.setFileSizeMax(maxFileSize);
    servletFileUpload.setSizeMax(maxFileSize);
    Map<String, Object> map = new HashMap<String, Object>();
    List<?> list = servletFileUpload.parseRequest(request);

    if (list != null && list.size() > 0) {
        for (Iterator<?> iterator = list.iterator(); iterator.hasNext();) {
            FileItem item = (FileItem) iterator.next();

            if (item.isFormField()) {
                logger.debug("form field: {}, {}", item.getFieldName(), item.toString());
                map.put(item.getFieldName(), item.getString("utf-8"));
            } else {
                logger.debug("file field: {}", item.getFieldName());
                map.put(item.getFieldName(), item);
            }
        }
    }
    return map;
}

From source file:admin.controller.ServletUploadFonts.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   ww  w.ja  v  a2s.  c o m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.processRequest(request, response);
    response.setContentType("text/html;charset=UTF-8");
    String filePath;
    String file_name = null, field_name, upload_path;
    RequestDispatcher request_dispatcher;
    String font_name = "", look_id;
    String font_family_name = "";
    PrintWriter out = response.getWriter();
    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;

    try {

        // Verify the content type
        String contentType = request.getContentType();
        if ((contentType.indexOf("multipart/form-data") >= 0)) {

            DiskFileItemFactory factory = new DiskFileItemFactory();
            // maximum size that will be stored in memory
            factory.setSizeThreshold(maxMemSize);
            // Location to save data that is larger than maxMemSize.
            factory.setRepository(new File(AppConstants.TMP_FOLDER));

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // maximum file size to be uploaded.
            upload.setSizeMax(maxFileSize);

            // Parse the request to get file items.
            List fileItems = upload.parseRequest(request);

            // Process the uploaded file items
            Iterator i = fileItems.iterator();

            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (fi.isFormField()) {
                    // Get the uploaded file parameters
                    field_name = fi.getFieldName();
                    if (field_name.equals("fontname")) {
                        font_name = fi.getString();
                    }
                    if (field_name.equals("fontstylecss")) {
                        font_family_name = fi.getString();
                    }

                } else {

                    //                        check = fonts.checkAvailability(font_name);
                    //                        if (check == false){

                    field_name = fi.getFieldName();
                    file_name = fi.getName();

                    if (file_name != "") {
                        File uploadDir = new File(AppConstants.BASE_FONT_UPLOAD_PATH);
                        if (!uploadDir.exists()) {
                            uploadDir.mkdirs();
                        }

                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();

                        filePath = AppConstants.BASE_FONT_UPLOAD_PATH + File.separator + file_name;
                        File storeFile = new File(filePath);

                        fi.write(storeFile);

                        out.println("Uploaded Filename: " + filePath + "<br>");
                    }
                    fonts.addFont(font_name, file_name, font_family_name);
                    response.sendRedirect(request.getContextPath() + "/admin/fontsfamily.jsp");

                    //                            }else {
                    //                                response.sendRedirect(request.getContextPath() + "/admin/fontsfamily.jsp?exist=exist");
                    //                            }
                }
            }
        }

    } catch (Exception e) {
        logger.log(Level.SEVERE, "Exception while uploading fonts", e);
    }
}

From source file:controller.UploadServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // checks if the request actually contains upload file
    if (!ServletFileUpload.isMultipartContent(request)) {
        // if not, we stop here
        PrintWriter writer = response.getWriter();
        writer.println("Error: Form must has enctype=multipart/form-data.");
        writer.flush();/*from  w w w.java  2s  .co m*/
        return;
    }
    // configures upload settings
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // sets memory threshold - beyond which files are stored in disk 
    factory.setSizeThreshold(MEMORY_THRESHOLD);
    // sets temporary location to store files
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    ServletFileUpload upload = new ServletFileUpload(factory);

    // sets maximum size of upload file
    upload.setFileSizeMax(MAX_FILE_SIZE);

    // sets maximum size of request (include file + form data)
    upload.setSizeMax(MAX_REQUEST_SIZE);

    // constructs the directory path to store upload file
    // this path is relative to application's directory
    String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;

    // creates the directory if it does not exist
    File uploadDir = new File(uploadPath);
    if (!uploadDir.exists()) {
        uploadDir.mkdir();
    }

    try {

        List<FileItem> formItems = upload.parseRequest(request);

        if (formItems != null && formItems.size() > 0) {
            // iterates over form's fields
            for (FileItem item : formItems) {
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    String filePath = uploadPath + File.separator + fileName;
                    File storeFile = new File(filePath);

                    // saves the file on disk
                    item.write(storeFile);
                    request.setAttribute("msg", UPLOAD_DIRECTORY + "/" + fileName);
                    request.setAttribute("message",
                            "Upload has been done successfully >>" + UPLOAD_DIRECTORY + "/" + fileName);
                }
            }
        }
    } catch (Exception ex) {
        request.setAttribute("message", "There was an error: " + ex.getMessage());
    }
    // redirects client to message page
    getServletContext().getRequestDispatcher("/message.jsp").forward(request, response);
}

From source file:com.github.davidcarboni.encryptedfileupload.SizesTest.java

/** Checks, whether the maxSize works.
 *//*from   ww w.  j  a  v a 2  s  .  c o m*/
@Test
public void testMaxSizeLimit() throws IOException, FileUploadException {
    final String request = "-----1234\r\n"
            + "Content-Disposition: form-data; name=\"file1\"; filename=\"foo1.tab\"\r\n"
            + "Content-Type: text/whatever\r\n" + "Content-Length: 10\r\n" + "\r\n"
            + "This is the content of the file\n" + "\r\n" + "-----1234\r\n"
            + "Content-Disposition: form-data; name=\"file2\"; filename=\"foo2.tab\"\r\n"
            + "Content-Type: text/whatever\r\n" + "\r\n" + "This is the content of the file\n" + "\r\n"
            + "-----1234--\r\n";

    ServletFileUpload upload = new ServletFileUpload(new EncryptedFileItemFactory());
    upload.setFileSizeMax(-1);
    upload.setSizeMax(200);

    MockHttpServletRequest req = new MockHttpServletRequest(request.getBytes("US-ASCII"), CONTENT_TYPE);
    try {
        upload.parseRequest(req);
        fail("Expected exception.");
    } catch (FileUploadBase.SizeLimitExceededException e) {
        assertEquals(200, e.getPermittedSize());
    }

}

From source file:admin.controller.ServletAddLooks.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//ww  w  .j  a v a 2 s . c o m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    super.processRequest(request, response);
    String filePath;
    String fileName, fieldName;
    Looks look;
    RequestDispatcher request_dispatcher;
    String look_name = null;
    Integer organization_id = 0;
    boolean check;
    look = new Looks();
    check = false;

    response.setContentType("text/html;charset=UTF-8");
    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {
        String uploadPath = AppConstants.LOOK_IMAGES_HOME;

        // Verify the content type
        String contentType = request.getContentType();
        if ((contentType.indexOf("multipart/form-data") >= 0)) {

            DiskFileItemFactory factory = new DiskFileItemFactory();
            // maximum size that will be stored in memory
            factory.setSizeThreshold(maxMemSize);
            // Location to save data that is larger than maxMemSize.
            factory.setRepository(new File("/tmp"));

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // maximum file size to be uploaded.
            upload.setSizeMax(maxFileSize);

            // Parse the request to get file items.
            List fileItems = upload.parseRequest(request);

            // Process the uploaded file items
            Iterator i = fileItems.iterator();

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

                if (fi.isFormField()) {
                    // Get the uploaded file parameters
                    fieldName = fi.getFieldName();
                    try {
                        if (fieldName.equals("lookname")) {
                            look_name = fi.getString();
                        }
                        if (fieldName.equals("organization")) {
                            organization_id = Integer.parseInt(fi.getString());
                        }
                    } catch (Exception e) {
                        logger.log(Level.SEVERE, "Exception while getting the look_name and organization_id",
                                e);
                    }
                } else {
                    check = look.checkAvailability(look_name, organization_id);

                    if (check == false) {
                        fieldName = fi.getFieldName();
                        fileName = fi.getName();

                        File uploadDir = new File(uploadPath);
                        if (!uploadDir.exists()) {
                            uploadDir.mkdirs();
                        }

                        //                            int inStr = fileName.indexOf(".");
                        //                            String Str = fileName.substring(0, inStr);
                        //
                        //                            fileName = look_name + "_" + Str + ".png";
                        fileName = look_name + "_" + fileName;
                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();

                        filePath = uploadPath + File.separator + fileName;
                        File storeFile = new File(filePath);

                        fi.write(storeFile);

                        look.addLooks(look_name, fileName, organization_id);
                        response.sendRedirect(request.getContextPath() + "/admin/looks.jsp");
                    } else {
                        response.sendRedirect(request.getContextPath() + "/admin/looks.jsp?exist=exist");
                    }

                }
            }

        } else {
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Exception while uploading the Looks image", ex);
    }
}

From source file:gov.nih.nci.caarray.web.fileupload.MonitoredMultiPartRequest.java

/**
 * {@inheritDoc}//from  w  w w  .ja v a2  s.  c om
 */
@SuppressWarnings({ "unchecked", "PMD.CyclomaticComplexity" })
public void parse(HttpServletRequest servletRequest, String saveDir) throws IOException {
    DiskFileItemFactory fac = new DiskFileItemFactory();
    fac.setSizeThreshold(0);
    if (saveDir != null) {
        fac.setRepository(new File(saveDir));
    }
    ProgressMonitor monitor = null;
    try {
        ServletFileUpload upload = new ServletFileUpload(fac);
        upload.setSizeMax(maxSize);
        monitor = new ProgressMonitor();
        upload.setProgressListener(monitor);
        String uploadKey = getUploadKey(servletRequest);
        servletRequest.getSession().setAttribute(uploadKey, monitor);
        List<FileItem> items = (List<FileItem>) upload.parseRequest(createRequestContext(servletRequest));
        for (FileItem item : items) {
            LOG.debug((new StringBuilder()).append("Found item ").append(item.getFieldName()).toString());
            if (item.isFormField()) {
                handleFormField(servletRequest, item);
            } else {
                handleFileUpload(item);
            }
        }
        handleChunkedUploadHeaders(servletRequest);
    } catch (FileUploadException e) {
        if (monitor != null) {
            monitor.abort();
        }
        LOG.warn("Error processing upload", e);
        errors.add(e.getMessage());
    }
}

From source file:com.aspectran.web.activity.request.multipart.MultipartFormDataParser.java

/**
 * Parse the given servlet request, resolving its multipart elements.
 *
 * @param requestAdapter the request adapter
 * @throws MultipartRequestException if multipart resolution failed
 *///  w  w  w. ja va2s  .co  m
public void parse(RequestAdapter requestAdapter) {
    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(DEFAULT_SIZE_THRESHOLD);

        if (temporaryFilePath != null) {
            File repository = new File(temporaryFilePath);
            if (!repository.exists() && !repository.mkdirs()) {
                throw new IllegalArgumentException(
                        "Given temporaryFilePath [" + temporaryFilePath + "] could not be created.");
            }
            factory.setRepository(repository);
        }

        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(maxRequestSize);
        upload.setHeaderEncoding(requestAdapter.getCharacterEncoding());

        Map<String, List<FileItem>> fileItemListMap;

        try {
            RequestContext requestContext = createRequestContext(requestAdapter.getAdaptee());
            fileItemListMap = upload.parseParameterMap(requestContext);
        } catch (SizeLimitExceededException e) {
            log.warn("Max length exceeded. multipart.maxRequestSize: " + maxRequestSize);
            requestAdapter.setMaxLengthExceeded(true);
            return;
        }

        parseMultipart(fileItemListMap, requestAdapter);
    } catch (Exception e) {
        throw new MultipartRequestException("Could not parse multipart servlet request.", e);
    }
}

From source file:Com.Dispatcher.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//  w w  w .j  a  v  a 2 s.  co  m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    File file;

    Boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {
        return;
    }

    // Create a session object if it is already not  created.
    HttpSession session = request.getSession(true);
    // Get session creation time.
    Date createTime = new Date(session.getCreationTime());
    // Get last access time of this web page.
    Date lastAccessTime = new Date(session.getLastAccessedTime());

    String visitCountKey = new String("visitCount");
    String userIDKey = new String("userID");
    String userID = new String("ABCD");
    Integer visitCount = (Integer) session.getAttribute(visitCountKey);

    // Check if this is new comer on your web page.
    if (visitCount == null) {

        session.setAttribute(userIDKey, userID);
    } else {

        visitCount++;
        userID = (String) session.getAttribute(userIDKey);
    }
    session.setAttribute(visitCountKey, visitCount);

    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize.
    factory.setRepository(new File(fileRepository));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);

    try {
        // Parse the request to get file items
        List fileItems = upload.parseRequest(request);
        // Process the uploaded file items
        Iterator i = fileItems.iterator();
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                String fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();
                // Write the file to server in "/uploads/{sessionID}/"   
                String clientDataPath = getServletContext().getInitParameter("clientFolder");
                // TODO clear the client folder here
                // FileUtils.deleteDirectory(new File("clientDataPath"));
                if (fileName.lastIndexOf("\\") >= 0) {

                    File input = new File(clientDataPath + session.getId() + "/input/");
                    input.mkdirs();
                    File output = new File(clientDataPath + session.getId() + "/output/");
                    output.mkdirs();
                    session.setAttribute("inputFolder", clientDataPath + session.getId() + "/input/");
                    session.setAttribute("outputFolder", clientDataPath + session.getId() + "/output/");

                    file = new File(
                            input.getAbsolutePath() + "/" + fileName.substring(fileName.lastIndexOf("/")));
                } else {
                    File input = new File(clientDataPath + session.getId() + "/input/");
                    input.mkdirs();
                    File output = new File(clientDataPath + session.getId() + "/output/");
                    output.mkdirs();
                    session.setAttribute("inputFolder", clientDataPath + session.getId() + "/input/");
                    session.setAttribute("outputFolder", clientDataPath + session.getId() + "/output/");

                    file = new File(
                            input.getAbsolutePath() + "/" + fileName.substring(fileName.lastIndexOf("/") + 1));
                }
                fi.write(file);
            }
        }
    } catch (Exception ex) {
        System.out.println("Failure: File Upload");
        System.out.println(ex);
        //TODO show error page for website
    }
    System.out.println("file uploaded");
    // TODO make the fileRepository Folder generic so it doesnt need to be changed
    // for each migration of the program to a different server
    File input = new File((String) session.getAttribute("inputFolder"));
    File output = new File((String) session.getAttribute("outputFolder"));
    File profile = new File(getServletContext().getInitParameter("profileFolder"));
    File hintsXML = new File(getServletContext().getInitParameter("hintsXML"));

    System.out.println("folders created");

    Controller controller = new Controller(input, output, profile, hintsXML);
    HashMap initialArtifacts = controller.initialArtifacts();
    session.setAttribute("Controller", controller);

    System.out.println("Initialisation of profiles for session (" + session.getId() + ") is complete\n"
            + "Awaiting user to update parameters to generate next generation of results.\n");

    String json = new Gson().toJson(initialArtifacts);
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}

From source file:controllers.ServerController.java

public void uploadFile(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    String UPLOAD_DIRECTORY = "/opt/ppd";
    int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB
    int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
    int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB

    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(MEMORY_THRESHOLD);
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(MAX_FILE_SIZE);
    upload.setSizeMax(MAX_REQUEST_SIZE);

    File uploadDir = new File(UPLOAD_DIRECTORY);
    if (!uploadDir.exists())
        uploadDir.mkdir();/*ww w.  j a  va2  s.  c om*/

    try {
        // parses the request's content to extract file data
        @SuppressWarnings("unchecked")
        List<FileItem> formItems = upload.parseRequest(request);
        if (formItems != null && formItems.size() > 0) {
            // iterates over form's fields
            for (FileItem item : formItems) {
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    String filePath = UPLOAD_DIRECTORY + File.separator + fileName;
                    File storeFile = new File(filePath);
                    item.write(storeFile);
                    PrintWriter out = response.getWriter();
                    Runtime runtime = Runtime.getRuntime();
                    Process process = runtime.exec("/opt/script.sh " + fileName);
                    out.write("uplad success");
                    out.close();
                }
            }
        }
    } catch (Exception ex) {
        PrintWriter out = response.getWriter();
        out.write("There was an error: " + ex.getMessage().toString());
        out.close();
    }

}