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:voucherShop.ControllerVoucher.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   w w  w.j  a v  a 2s .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
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    //ServletContext context = pageContext.getServletContext();
    String filePath = getServletContext().getInitParameter("file-upload");
    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("c:\\temp"));

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // maximum file size to be uploaded.
        upload.setSizeMax(maxFileSize);
        out.println("1");
        try {
            out.println("2");
            // Parse the request to get file items.
            List fileItems = upload.parseRequest(request);

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

            out.println("<html>");
            out.println("<head>");
            out.println("<title>JSP File upload</title>");
            out.println("</head>");
            out.println("<body>");
            while (i.hasNext()) {
                out.println("3");
                FileItem fi = (FileItem) i.next();
                if (!fi.isFormField()) {
                    out.println("4");
                    // Get the uploaded file parameters
                    String fieldName = fi.getFieldName();
                    String fileName = fi.getName();
                    boolean isInMemory = fi.isInMemory();
                    long sizeInBytes = fi.getSize();
                    out.println(fileName);
                    // Write the file
                    if (fileName.lastIndexOf("\\") >= 0) {
                        file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                    } else {
                        file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
                    }
                    out.println(filePath);
                    try {

                        fi.write(file);
                    } catch (Exception ex) {
                        System.out.println("li .....");
                        System.out.println(ex);
                    }
                    out.println("4");
                    out.println("Uploaded Filename: " + filePath + fileName + "<br>");
                } else {
                    out.println("sai ding dan");
                }
            }
            out.println("</body>");
            out.println("</html>");
        } catch (Exception ex) {
            System.out.println(ex);

        }
    } else {
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<p>No file uploaded</p>");
        out.println("</body>");
        out.println("</html>");
    }
}

From source file:web.ZipUploadController.java

/**
 * This method is called by the spring framework. The configuration
 * for this controller to be invoked is based on the pagetype and
 * is set in the urlMapping property in the spring config file.
 *
 * @param request the <code>HttpServletRequest</code>
 * @param response the <code>HttpServletResponse</code>
 * @throws ServletException//  w  ww . j  a  v a 2s .c om
 * @throws IOException
 * @return ModelAndView this instance is returned to spring
 */
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {
        ModelAndView modelAndView = super.handleRequest(request, response);
    } catch (Exception e) {
        return handleError("error in handleRequest", e);
    }

    outOfSession(request, response);

    if (RegexStrUtil.isNull(login) && RegexStrUtil.isNull(member)) {
        return handleUserpageError("Login & member are null.");
    }

    String category = request.getParameter(DbConstants.CATEGORY);
    boolean isCobrand = false;
    if (!RegexStrUtil.isNull(request.getParameter(DbConstants.IS_COBRAND))) {
        isCobrand = request.getParameter(DbConstants.IS_COBRAND).equals((Object) "1");
    }

    if ((!RegexStrUtil.isNull(category) && category.equals(DbConstants.FILE_CATEGORY)) || isCobrand) {
        if (!WebUtil.isLicenseProfessional(login)) {
            return handleError(
                    "Cannot access user carryon features or cobrand user in deluxe version." + login);
        }
    }
    if (RegexStrUtil.isNull(category)) {
        return handleError("category is null in CarryonupdateController. " + login);
    }

    if (daoMapper == null) {
        return handleError("DaoMapper is null in carryon update.");
    }

    CarryonDao carryonDao = (CarryonDao) daoMapper.getDao(DbConstants.CARRYON);
    if (carryonDao == null) {
        return handleError("CarryonDao is null for carryon update.");
    }

    byte[] blob = null;
    String mtype = null;
    if (!RegexStrUtil.isNull(category)) {
        int catVal = new Integer(category).intValue();
        if (catVal < GlobalConst.categoryMinSize || catVal > GlobalConst.categoryMaxSize) {
            return handleError("category values are not correct" + catVal);
        }
    }

    CobrandDao cobrandDao = (CobrandDao) daoMapper.getDao(DbConstants.COBRAND);
    if (cobrandDao == null) {
        return handleError("cobrandDao is null for CarryonupdateController");
    }

    DisplaypageDao displayDao = (DisplaypageDao) daoMapper.getDao(DbConstants.DISPLAY_PAGE);
    if (displayDao == null) {
        return handleError("displayDao is null for CarryonupdateController");
    }

    Displaypage displaypage = null;
    Userpage cobrand = null;
    try {
        displaypage = displayDao.getDisplaypage(login, DbConstants.READ_FROM_SLAVE);
        cobrand = cobrandDao.getUserCobrand(loginInfo.getValue(DbConstants.LOGIN_ID));
    } catch (BaseDaoException e) {
        return handleError("Exception occurred in getDisplaypage() for login " + login, e);
    }

    System.setProperty("jmagick.systemclassloader", "no");

    List fileList = null;
    ServletFileUpload upload = null;
    try {
        // Check that we have a file upload request
        boolean isMultipart = FileUpload.isMultipartContent(request);
        if (isMultipart) {
            // Create a factory for disk-based file items
            DiskFileItemFactory factory = new DiskFileItemFactory();

            // Set factory constraints
            factory.setSizeThreshold(maxMemorySize.intValue());
            //factory.setRepository(new File(tempDirectory));

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

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

            // Parse the request
            fileList = upload.parseRequest(request);

            long fieldsize = 0;
            String fieldname, fieldvalue;
            fieldname = fieldvalue = null;

            // educate the fieldnames to this form by using the setFieldName()
            String label = "btitle";
            String caption = "";
            String tagsLabel = DbConstants.USER_TAGS;
            String fileName = null;
            String usertags = null;
            String btitle = null;

            // Process the uploaded items
            Iterator iter = fileList.iterator();
            while (iter.hasNext()) {
                FileItem fileItem = (FileItem) iter.next();
                if (fileItem.isFormField()) {
                    fileItem.setFieldName(label);
                    fieldname = fileItem.getFieldName();
                    logger.info("fieldname = " + fieldname);
                    if (fieldname.equalsIgnoreCase(DbConstants.USER_TAGS)) {
                        usertags = fileItem.getString();
                        label = "";
                    } else {
                        if (fieldname.equalsIgnoreCase("btitle")) {
                            btitle = fileItem.getString();
                            label = DbConstants.CAPTION;
                        } else {
                            if (fieldname.equalsIgnoreCase("caption")) {
                                caption = fileItem.getString();
                                label = DbConstants.USER_TAGS;
                            } else {
                                fieldvalue = fileItem.getString();
                            }
                        }
                    }
                } else {
                    logger.info("contentType = " + fileItem.getContentType());
                    if (fileItem.getContentType().contains("zip")) {
                        List entries = zipUtil.getEntries(fileItem.get());
                        logger.info("num entries = " + entries.size());
                        Iterator iter1 = entries.iterator();
                        while (iter1.hasNext()) {
                            Media media = (Media) iter1.next();
                            blob = media.getData();
                            mtype = mimeMap.getMimeType(zipUtil.getSuffix(media.getName()));
                            fileName = media.getName();
                            fieldsize = media.getData().length;
                            if (RegexStrUtil.isNull(btitle)) {
                                btitle = fileName;
                            }
                            if ((fieldsize <= 0) || (RegexStrUtil.isNull(mtype))
                                    || (RegexStrUtil.isNull(btitle)) || (blob == null)) {
                                return handleError(
                                        "fieldsize/mtype/btitle/blob one of them is empty, cannot upload files.");
                            }
                            if (!isCobrand) {
                                if (btitle.length() > GlobalConst.blobTitleSize) {
                                    btitle = btitle.substring(0, GlobalConst.blobTitleSize);
                                }
                                int zoom = 100;
                                if (!RegexStrUtil.isNull(usertags)) {
                                    if (usertags.length() > GlobalConst.usertagsSize) {
                                        usertags = usertags.substring(0, GlobalConst.usertagsSize);
                                    }
                                    usertags = RegexStrUtil.goodText(usertags);
                                }
                                if (!RegexStrUtil.isNull(caption)) {
                                    if (caption.length() > GlobalConst.refererSize) {
                                        caption = caption.substring(0, GlobalConst.refererSize);
                                    }
                                    caption = RegexStrUtil.goodText(caption);
                                }
                                boolean publishPhoto = displayDao.getDisplayPhotos(login,
                                        DbConstants.READ_FROM_SLAVE);
                                carryonDao.addCarryon(fieldsize, category, mtype, RegexStrUtil.goodText(btitle),
                                        blob, zoom, loginInfo.getValue(DbConstants.LOGIN_ID), login, usertags,
                                        caption, publishPhoto);

                            }
                        }
                    } else {
                        if (!validImage.isValid(fileItem.getContentType())) {
                            logger.warn("Found unexpected content type in upload, ignoring  "
                                    + fileItem.getContentType());
                            continue;
                        }
                        logger.debug("Is not a form field");
                        blob = fileItem.get();
                        mtype = fileItem.getContentType();
                        fileName = fileItem.getName();
                        fieldsize = fileItem.getSize();
                        if (RegexStrUtil.isNull(btitle)) {
                            btitle = fileName;
                        }
                        if ((fieldsize <= 0) || (RegexStrUtil.isNull(mtype)) || (RegexStrUtil.isNull(btitle))
                                || (blob == null)) {
                            return handleError(
                                    "fieldsize/mtype/btitle/blob one of them is empty, cannot upload files.");
                        }
                        if (isCobrand)
                            break;
                        if (!isCobrand) {
                            if (btitle.length() > GlobalConst.blobTitleSize) {
                                btitle = btitle.substring(0, GlobalConst.blobTitleSize);
                            }
                            int zoom = 100;
                            if (!RegexStrUtil.isNull(usertags)) {
                                if (usertags.length() > GlobalConst.usertagsSize) {
                                    usertags = usertags.substring(0, GlobalConst.usertagsSize);
                                }
                                usertags = RegexStrUtil.goodText(usertags);
                            }
                            if (!RegexStrUtil.isNull(caption)) {
                                if (caption.length() > GlobalConst.refererSize) {
                                    caption = caption.substring(0, GlobalConst.refererSize);
                                }
                                caption = RegexStrUtil.goodText(caption);
                            }
                            boolean publishPhoto = displayDao.getDisplayPhotos(login,
                                    DbConstants.READ_FROM_SLAVE);
                            carryonDao.addCarryon(fieldsize, category, mtype, RegexStrUtil.goodText(btitle),
                                    blob, zoom, loginInfo.getValue(DbConstants.LOGIN_ID), login, usertags,
                                    caption, publishPhoto);

                        }
                    }
                }
            }
        } else {
            return handleError("Did not get a multipart request");
        }
    } catch (Exception e) {
        return handleError("Exception occurred in addCarryon/addCobrandUserStreamBlo()", e);
    }

    if (isCobrand) {
        try {
            String ftype = request.getParameter(DbConstants.TYPE);
            if (RegexStrUtil.isNull(ftype)) {
                return handleError("ftype is null, CarryonUpdateController() ");
            }
            if (ftype.equals(DbConstants.COBRAND_HEADER) || ftype.equals(DbConstants.COBRAND_FOOTER)) {
                cobrandDao.addUserCobrand(blob, ftype, loginInfo.getValue(DbConstants.LOGIN_ID), login);
            } else {
                return handleError("cobrand type is not a header or footer in CarryonUpdateController ");
            }
        } catch (BaseDaoException e) {
            return handleError("Exception occurred in addCobrandUserStreamBlo()", e);
        }
    }

    /**
    * list the files
    */
    String loginId = loginInfo.getValue(DbConstants.LOGIN_ID);
    List carryon = null;
    List tagList = null;
    HashSet tagSet = null;
    try {
        carryon = carryonDao.getCarryonByCategory(loginId, category, DbConstants.READ_FROM_MASTER);
        tagList = carryonDao.getTags(loginId, DbConstants.READ_FROM_MASTER);
        tagSet = carryonDao.getUniqueTags(tagList);
    } catch (BaseDaoException e) {
        return handleError(
                "Exception occurred in getCarryonByCategory()/getTags carryon update for login " + login, e);
    }

    /**
    * display information about the files, if the category of the blobs is files category(1)
    */
    String viewName = DbConstants.EDIT_PHOTOS;
    if (category.equals(DbConstants.FILE_CATEGORY)) {
        viewName = DbConstants.EDIT_FILES;
    }

    Map myModel = new HashMap();
    myModel.put(viewName, carryon);
    myModel.put(DbConstants.COBRAND, cobrand);
    if (tagSet != null) {
        myModel.put(DbConstants.USER_TAGS, RegexStrUtil.goodText(tagSet.toString()));
    }
    myModel.put(DbConstants.LOGIN_INFO, loginInfo);
    myModel.put(DbConstants.DISPLAY_PAGE, displaypage);
    myModel.put(DbConstants.USER_PAGE, userpage);
    myModel.put(DbConstants.SHARE_INFO, shareInfo);
    myModel.put(DbConstants.VISITOR_PAGE, memberUserpage);
    myModel.put(DbConstants.DIR_EXISTS, rbDirectoryExists);
    myModel.put(DbConstants.BUSINESS_EXISTS, isBizExists(login));
    return new ModelAndView(viewName, "model", myModel);
}