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:com.uniquesoft.uidl.servlet.UploadServlet.java

/**
 * This method parses the submit action, puts in session a listener where the
 * progress status is updated, and eventually stores the received data in
 * the user session./*from  w ww.ja  v a  2  s.com*/
 * 
 * returns null in the case of success or a string with the error
 * 
 */
@SuppressWarnings("unchecked")
protected String parsePostRequest(HttpServletRequest request, HttpServletResponse response) {

    try {
        String delay = request.getParameter(PARAM_DELAY);
        uploadDelay = Integer.parseInt(delay);
    } catch (Exception e) {
    }

    HttpSession session = request.getSession();

    logger.debug("UPLOAD-SERVLET (" + session.getId() + ") new upload request received.");

    AbstractUploadListener listener = getCurrentListener(request);
    if (listener != null) {
        if (listener.isFrozen() || listener.isCanceled() || listener.getPercent() >= 100) {
            removeCurrentListener(request);
        } else {
            String error = getMessage("busy");
            logger.error("UPLOAD-SERVLET (" + session.getId() + ") " + error);
            return error;
        }
    }
    // Create a file upload progress listener, and put it in the user session,
    // so the browser can use ajax to query status of the upload process
    listener = createNewListener(request);

    List<FileItem> uploadedItems;
    try {

        // Call to a method which the user can override
        checkRequest(request);

        // Create the factory used for uploading files,
        FileItemFactory factory = getFileItemFactory(getContentLength(request));
        ServletFileUpload uploader = new ServletFileUpload(factory);
        uploader.setSizeMax(maxSize);
        uploader.setProgressListener(listener);

        // Receive the files
        logger.debug("UPLOAD-SERVLET (" + session.getId() + ") parsing HTTP POST request ");
        uploadedItems = uploader.parseRequest(request);
        session.removeAttribute(getSessionLastFilesKey(request));
        logger.debug("UPLOAD-SERVLET (" + session.getId() + ") parsed request, " + uploadedItems.size()
                + " items received.");

        // Received files are put in session
        List<FileItem> sessionFiles = getMySessionFileItems(request);
        if (sessionFiles == null) {
            sessionFiles = new ArrayList<FileItem>();
        }

        String error = "";

        if (uploadedItems.size() > 0) {

            // We append to the field name the sequence of the uploaded file
            int cnt = 0;
            for (FileItem i : uploadedItems) {
                if (!i.isFormField()) {
                    i.setFieldName(i.getFieldName().replace(UConsts.MULTI_SUFFIX, "") + "-" + cnt++);
                }
            }

            sessionFiles.addAll(uploadedItems);
            String msg = "";
            for (FileItem i : sessionFiles) {
                msg += i.getFieldName() + " => " + i.getName() + "(" + i.getSize() + " bytes),";
            }
            logger.debug("UPLOAD-SERVLET (" + session.getId() + ") puting items in session: " + msg);
            session.setAttribute(getSessionFilesKey(request), sessionFiles);
            session.setAttribute(getSessionLastFilesKey(request), uploadedItems);
        } else {
            logger.error("UPLOAD-SERVLET (" + session.getId() + ") error NO DATA received ");
            error += getMessage("no_data");
        }

        return error.length() > 0 ? error : null;

        // So much silly questions in the list about this issue.  
    } catch (LinkageError e) {
        logger.error("UPLOAD-SERVLET (" + request.getSession().getId() + ") Exception: " + e.getMessage() + "\n"
                + stackTraceToString(e));
        RuntimeException ex = new UploadActionException(getMessage("restricted", e.getMessage()), e);
        listener.setException(ex);
        throw ex;
    } catch (SizeLimitExceededException e) {
        RuntimeException ex = new UploadSizeLimitException(e.getPermittedSize(), e.getActualSize());
        listener.setException(ex);
        throw ex;
    } catch (UploadSizeLimitException e) {
        listener.setException(e);
        throw e;
    } catch (UploadCanceledException e) {
        listener.setException(e);
        throw e;
    } catch (UploadTimeoutException e) {
        listener.setException(e);
        throw e;
    } catch (Throwable e) {
        logger.error("UPLOAD-SERVLET (" + request.getSession().getId() + ") Unexpected Exception -> "
                + e.getMessage() + "\n" + stackTraceToString(e));
        e.printStackTrace();
        RuntimeException ex = new UploadException(e);
        listener.setException(ex);
        throw ex;
    }
}

From source file:gwtupload.server.UploadServlet.java

/**
 * This method parses the submit action, puts in session a listener where the
 * progress status is updated, and eventually stores the received data in
 * the user session.//from w ww. ja  va 2  s  .  c  om
 *
 * returns null in the case of success or a string with the error
 *
 */
protected String parsePostRequest(HttpServletRequest request, HttpServletResponse response) {
    try {
        String delay = request.getParameter(PARAM_DELAY);
        String maxFilesize = request.getParameter(PARAM_MAX_FILE_SIZE);
        maxSize = maxFilesize != null && maxFilesize.matches("[0-9]*") ? Long.parseLong(maxFilesize) : maxSize;
        uploadDelay = Integer.parseInt(delay);
    } catch (Exception e) {
    }

    HttpSession session = request.getSession();

    logger.debug("UPLOAD-SERVLET (" + session.getId() + ") new upload request received.");

    AbstractUploadListener listener = getCurrentListener(request);
    if (listener != null) {
        if (listener.isFrozen() || listener.isCanceled() || listener.getPercent() >= 100) {
            removeCurrentListener(request);
        } else {
            String error = getMessage("busy");
            logger.error("UPLOAD-SERVLET (" + session.getId() + ") " + error);
            return error;
        }
    }

    // Create a file upload progress listener, and put it in the user session,
    // so the browser can use ajax to query status of the upload process
    listener = createNewListener(request);

    List<FileItem> uploadedItems;
    try {

        // Call to a method which the user can override
        checkRequest(request);

        // Create the factory used for uploading files,
        FileItemFactory factory = getFileItemFactory(getContentLength(request));
        ServletFileUpload uploader = new ServletFileUpload(factory);
        uploader.setSizeMax(maxSize);
        uploader.setFileSizeMax(maxFileSize);
        uploader.setProgressListener(listener);

        // Receive the files
        logger.debug("UPLOAD-SERVLET (" + session.getId() + ") parsing HTTP POST request ");
        uploadedItems = uploader.parseRequest(request);
        session.removeAttribute(getSessionLastFilesKey(request));
        logger.debug("UPLOAD-SERVLET (" + session.getId() + ") parsed request, " + uploadedItems.size()
                + " items received.");

        // Received files are put in session
        List<FileItem> sessionFiles = getMySessionFileItems(request);
        if (sessionFiles == null) {
            sessionFiles = new ArrayList<FileItem>();
        }

        String error = "";
        if (uploadedItems.size() > 0) {
            sessionFiles.addAll(uploadedItems);
            String msg = "";
            for (FileItem i : sessionFiles) {
                msg += i.getFieldName() + " => " + i.getName() + "(" + i.getSize() + " bytes),";
            }
            logger.debug("UPLOAD-SERVLET (" + session.getId() + ") puting items in session: " + msg);
            session.setAttribute(getSessionFilesKey(request), sessionFiles);
            session.setAttribute(getSessionLastFilesKey(request), uploadedItems);
        } else if (!isAppEngine()) {
            logger.error("UPLOAD-SERVLET (" + session.getId() + ") error NO DATA received ");
            error += getMessage("no_data");
        }
        return error.length() > 0 ? error : null;

        // So much silly questions in the list about this issue.
    } catch (LinkageError e) {
        logger.error("UPLOAD-SERVLET (" + request.getSession().getId() + ") Exception: " + e.getMessage() + "\n"
                + stackTraceToString(e));
        RuntimeException ex = new UploadActionException(getMessage("restricted", e.getMessage()), e);
        listener.setException(ex);
        throw ex;
    } catch (SizeLimitExceededException e) {
        RuntimeException ex = new UploadSizeLimitException(e.getPermittedSize(), e.getActualSize());
        listener.setException(ex);
        throw ex;
    } catch (UploadSizeLimitException e) {
        listener.setException(e);
        throw e;
    } catch (UploadCanceledException e) {
        listener.setException(e);
        throw e;
    } catch (UploadTimeoutException e) {
        listener.setException(e);
        throw e;
    } catch (Throwable e) {
        logger.error("UPLOAD-SERVLET (" + request.getSession().getId() + ") Unexpected Exception -> "
                + e.getMessage(), e);
        e.printStackTrace();
        RuntimeException ex = new UploadException(e);
        listener.setException(ex);
        throw ex;
    }
}

From source file:com.esd.cs.worker.WorkerController.java

/**
 * ?/* ww w . j av  a 2  s .co m*/
 * 
 * @param request
 * @param response
 * @return
 */
public Map<String, String> importfile(String upLoadPath, HttpServletRequest request,
        HttpServletResponse response) {
    // ???
    // String fileType = "xls";
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // 
    factory.setSizeThreshold(5 * 1024);
    // 
    factory.setRepository(new File(upLoadPath));
    ServletFileUpload fileUpload = new ServletFileUpload(factory);
    Map<String, String> result = new HashMap<String, String>();

    if (LoadUpFileMaxSize != null && !StringUtils.equals(LoadUpFileMaxSize.trim(), "")) {
        // ?
        fileUpload.setSizeMax(Integer.valueOf(LoadUpFileMaxSize) * 1024 * 1024);
    }
    try {
        // ?
        List<FileItem> items = fileUpload.parseRequest(request);
        for (FileItem item : items) {
            // ?
            if (!item.isFormField()) {
                // ??
                String fileName = item.getName();
                // ??
                String fileEnd = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                // ??
                String uuid = UUID.randomUUID().toString();
                // 
                StringBuffer sbRealPath = new StringBuffer();
                sbRealPath.append(upLoadPath).append(uuid).append(".").append(fileEnd);
                // 
                File file = new File(sbRealPath.toString());
                item.write(file);

                logger.info("?,filePath" + file.getPath());
                // 
                result.put("filePath", file.getPath());

                // form??
            } else {
                // item.getFieldName():??keyitem.getString()??value
                result.put(item.getFieldName(), item.getString());
            }
        }
    } catch (Exception e) {

        // ???
        result.put("fileError", ",??" + LoadUpFileMaxSize + "M!");
        logger.error("uplaodWorkerFileError:{}", e.getMessage());
        return result;
    }
    return result;
}

From source file:byps.http.HHttpServlet.java

protected void doHtmlUpload(HttpServletRequest request, HttpServletResponse response) throws IOException {
    if (log.isDebugEnabled())
        log.debug("doHtmlUpload(");

    try {/*from  w  w  w  .  ja  v a 2  s .c  om*/
        // NDC.push(hsess.getId());

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (!isMultipart) {
            throw new IllegalStateException("File upload must be sent as multipart/form-data.");
        }

        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory(HConstants.INCOMING_STREAM_BUFFER,
                getConfig().getTempDir());

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

        // Set overall request size constraint
        long maxSize = getHtmlUploadMaxSize();
        if (log.isDebugEnabled())
            log.debug("set max upload file size=" + maxSize);
        upload.setSizeMax(maxSize);

        // Parse the request
        @SuppressWarnings("unchecked")
        List<FileItem> items = upload.parseRequest(request);
        if (log.isDebugEnabled())
            log.debug("received #items=" + items.size());

        ArrayList<HFileUploadItem> uploadItems = new ArrayList<HFileUploadItem>();
        for (FileItem item : items) {

            String fieldName = item.getFieldName();
            if (log.isDebugEnabled())
                log.debug("fieldName=" + fieldName);
            String fileName = item.getName();
            if (log.isDebugEnabled())
                log.debug("fileName=" + fileName);
            boolean formField = item.isFormField();
            if (log.isDebugEnabled())
                log.debug("formField=" + formField);
            if (!formField && fileName.length() == 0)
                continue;
            long streamId = formField ? 0L
                    : (System.currentTimeMillis()
                            ^ ((((long) fileName.hashCode()) << 16L) | (long) System.identityHashCode(this))); // used as pseudo random number

            HFileUploadItem uploadItem = new HFileUploadItem(formField, fieldName, fileName,
                    item.getContentType(), item.getSize(), Long.toString(streamId));
            uploadItems.add(uploadItem);
            if (log.isDebugEnabled())
                log.debug("uploadItem=" + uploadItem);

            if (item.isFormField())
                continue;

            final BTargetId targetId = new BTargetId(getConfig().getMyServerId(), 0, streamId);
            getActiveMessages().addIncomingUploadStream(
                    new HFileUploadItemIncomingStream(item, targetId, getConfig().getTempDir()));

        }

        makeHtmlUploadResult(request, response, uploadItems);

    } catch (Throwable e) {
        if (log.isInfoEnabled())
            log.info("Failed to process message.", e);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().print(e.toString());
        response.getWriter().close();
    } finally {
        // NDC.pop();
    }

    if (log.isDebugEnabled())
        log.debug(")doHtmlUpload");
}

From source file:com.darksky.seller.SellerServlet.java

/**
 *   /*w  w  w  .java  2  s  .  c  o  m*/
 * ?
 * @param request
 * @param response
 * @throws Exception
 */
public void modifyShopInfo(HttpServletRequest request, HttpServletResponse response) throws Exception {
    System.out.println();
    System.out.println("--------------------shop modify info-----------------");
    /* ? */
    String sellerID = Seller.getSellerID();

    /* ? */

    String shopID = Shop.getShopID();
    String shopName = null;
    String shopTel = null;
    String shopIntroduction = null;
    String Notice = null;
    String shopAddress = null;
    String shopPhoto = null;

    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();

    ServletFileUpload sfu = new ServletFileUpload(diskFileItemFactory);
    ServletFileUpload sfu2 = new ServletFileUpload(diskFileItemFactory);
    // ?
    sfu.setHeaderEncoding("UTF-8");
    // ?2M
    sfu.setFileSizeMax(1024 * 1024 * 2);
    // ?10M
    sfu.setSizeMax(1024 * 1024 * 10);
    List<FileItem> itemList = sfu.parseRequest(request);

    List<FileItem> itemList2 = sfu2.parseRequest(request);

    FileItem a = null;

    for (FileItem fileItem : itemList) {

        if (!fileItem.isFormField()) {
            a = fileItem;

            System.out.println("QQQQQQQQQQQQQQQQ" + fileItem.toString() + "QQQQQQQQ");

        } else {
            String fieldName = fileItem.getFieldName();
            String value = fileItem.getString("utf-8");
            switch (fieldName) {
            case "shopName":
                shopName = value;
                break;
            case "shopTel":
                shopTel = value;
                break;
            case "shopIntroduction":
                shopIntroduction = value;
                break;
            case "Notice":
                Notice = value;
                break;
            case "shopPhoto":
                shopPhoto = value;
                break;
            case "shopAddress":
                shopAddress = value;
                break;

            default:
                break;
            }

        }

    }
    double randomNum = Math.random();
    shopPhoto = "image/" + shopID + "_" + randomNum + ".jpg";
    String savePath2 = getServletContext().getRealPath("");
    System.out.println("path2=" + savePath2);
    getDish(sellerID);

    String shopSql = null;
    if (a.getSize() != 0) {
        File file2 = new File(savePath2, shopPhoto);
        a.write(file2);

        shopSql = "update shop set shopName='" + shopName + "' , shopTel='" + shopTel + "' , shopIntroduction='"
                + shopIntroduction + "' , Notice='" + Notice + "' , shopAddress='" + shopAddress
                + "',shopPhoto='" + shopPhoto + "' where shopID='" + shopID + "'";
    }

    else {

        shopSql = "update shop set shopName='" + shopName + "' , shopTel='" + shopTel + "' , shopIntroduction='"
                + shopIntroduction + "' , Notice='" + Notice + "' , shopAddress='" + shopAddress
                + "' where shopID='" + shopID + "'";
    }

    System.out.println("shopSql: " + shopSql);

    try {
        statement.executeUpdate(shopSql);
    } catch (SQLException e) {
        e.printStackTrace();
    }

    getShop(Seller.getShopID());
    request.getSession().setAttribute("shop", Shop);

    System.out.println("--------------------shop modify info-----------------");
    System.out.println();

    request.getRequestDispatcher(".jsp").forward(request, response);
}

From source file:com.darksky.seller.SellerServlet.java

/**
 * * ? /*from  ww  w .j a  va2 s .c  o  m*/
 * @param request
 * @param response
 * @throws Exception
 */
public void addDish(HttpServletRequest request, HttpServletResponse response) throws Exception {
    System.out.println();
    System.out.println("-----------add dish--------------");
    String sellerID = Seller.getSellerID();
    String shopID = Seller.getShopID();
    String dishType = null;
    String dishName = null;
    String dishPrice = null;

    String dishStock = null;
    String dishIntroduction = null;

    if (ServletFileUpload.isMultipartContent(request)) {
        // String savePath = getServletContext().getRealPath("image");

        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();

        ServletFileUpload sfu = new ServletFileUpload(diskFileItemFactory);
        ServletFileUpload sfu2 = new ServletFileUpload(diskFileItemFactory);
        // ?
        sfu.setHeaderEncoding("UTF-8");
        // ?2M
        sfu.setFileSizeMax(1024 * 1024 * 2);
        // ?10M
        sfu.setSizeMax(1024 * 1024 * 10);
        List<FileItem> itemList = sfu.parseRequest(request);

        List<FileItem> itemList2 = sfu2.parseRequest(request);

        FileItem a = null;

        for (FileItem fileItem : itemList) {

            if (!fileItem.isFormField()) {
                a = fileItem;

            } else {
                String fieldName = fileItem.getFieldName();
                String value = fileItem.getString("utf-8");
                switch (fieldName) {
                case "dishName":
                    dishName = value;
                    break;
                case "dishPrice":
                    dishPrice = value;
                    break;

                case "dishIntroduction":
                    dishIntroduction = value;
                    break;
                case "dishStock":
                    dishStock = value;
                    break;
                case "dishType":
                    dishType = value;
                    break;
                default:
                    break;
                }

            }

        }

        String dishPhoto = "image/" + sellerID + "_" + dishName + ".jpg";
        String sql = "insert into dishinfo (dishName,dishType,dishPrice,dishPhoto,shopID,dishIntroduction,dishStock,sellerID) values('"
                + dishName + "','" + dishType + "','" + dishPrice + "','" + dishPhoto + "','" + shopID + "','"
                + dishIntroduction + "','" + dishStock + "','" + sellerID + "')";
        System.out.println(sql);

        String savePath2 = getServletContext().getRealPath("");
        System.out.println("path2=" + savePath2);

        File file1 = new File(savePath2, dishPhoto);
        System.out.println(
                ""
                        + a.toString());
        a.write(file1);
        System.out.println("?");

        try {
            statement.execute(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    getDish(sellerID);
    request.getSession().setAttribute("dish", DishList);
    request.getRequestDispatcher("?.jsp").forward(request, response);
    System.out.println("-----------add dish--------------");
    System.out.println();

}

From source file:com.darksky.seller.SellerServlet.java

/**
 * * ? //  www . ja va2  s .  c  o  m
 * @param request
 * @param response
 * @throws Exception
 */
public void modifyDish(HttpServletRequest request, HttpServletResponse response) throws Exception {

    System.out.println("-----------modify dish--------------");
    String sellerID = Seller.getSellerID();
    String dishType = null;
    String dishName = null;
    String dishPrice = null;
    String dishID = null;
    String dishIntroduction = null;
    String dishStock = null;

    if (ServletFileUpload.isMultipartContent(request)) {
        // String savePath = getServletContext().getRealPath("image");

        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();

        ServletFileUpload sfu = new ServletFileUpload(diskFileItemFactory);
        ServletFileUpload sfu2 = new ServletFileUpload(diskFileItemFactory);
        // ?
        sfu.setHeaderEncoding("UTF-8");
        // ?2M
        sfu.setFileSizeMax(1024 * 1024 * 2);
        // ?10M
        sfu.setSizeMax(1024 * 1024 * 10);
        List<FileItem> itemList = sfu.parseRequest(request);

        List<FileItem> itemList2 = sfu2.parseRequest(request);

        FileItem a = null;

        for (FileItem fileItem : itemList) {

            if (!fileItem.isFormField()) {
                a = fileItem;

            } else {
                String fieldName = fileItem.getFieldName();
                String value = fileItem.getString("utf-8");
                switch (fieldName) {
                case "dishName":
                    dishName = value;
                    System.out.println("!!!!!!!!!!!!!!!!!dishName=     " + dishName);
                    break;
                case "dishPrice":
                    dishPrice = value;
                    break;
                case "dishIntroduction":
                    dishIntroduction = value;
                    break;
                case "dishStock":
                    dishStock = value;
                    break;
                case "dishID":
                    dishID = value;
                    break;
                case "dishType":
                    dishType = value;
                    break;
                default:
                    break;
                }

            }

        }
        // ?
        double randomNum = Math.random();
        // request.setAttribute("randomNum", randomNum);

        String dishPhoto = "image/" + sellerID + "_" + dishName + "_" + randomNum + ".jpg";

        String savePath2 = getServletContext().getRealPath("");
        System.out.println("path2=" + savePath2);
        getDish(sellerID);
        File file1 = new File(savePath2, dishPhoto);

        String sql = null;
        if (a.getSize() != 0) {
            a.write(file1);

            sql = "update dishinfo set dishType='" + dishType + "',dishName='" + dishName + "',dishPrice='"
                    + dishPrice + "',dishPrice='" + dishPrice + "',dishIntroduction='" + dishIntroduction
                    + "',dishStock='" + dishStock + "',dishPhoto='" + dishPhoto + "' where dishID='" + dishID
                    + "'";
        } else {
            sql = "update dishinfo set dishType='" + dishType + "',dishName='" + dishName + "',dishPrice='"
                    + dishPrice + "',dishPrice='" + dishPrice + "',dishIntroduction='" + dishIntroduction
                    + "',dishStock='" + dishStock + "' where dishID='" + dishID + "'";
        }

        System.out.println(sql);

        try {
            statement.execute(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    getDish(sellerID);

    request.getSession().setAttribute("dish", DishList);
    request.getSession().setAttribute("sellerID", sellerID);
    System.out.println("**********************     sellerID=    " + sellerID + "**************");
    // this.sellerDish(request, response);

    request.getRequestDispatcher("?.jsp").forward(request, response);

}

From source file:com.beetle.framework.web.controller.UploadController.java

/**
 * use the overdue upload package/*from  www.j  av a  2  s.c o  m*/
 * 
 * @param webInput
 * @param request
 * @return
 * @throws ControllerException
 */
private View doupload(WebInput webInput, HttpServletRequest request) throws ControllerException {
    UploadForm fp = null;
    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload sfu = new ServletFileUpload(factory);
    List<?> fileItems = null;
    boolean openApiCase = false;
    try {
        IUpload upload = (IUpload) webInput.getRequest().getAttribute("UPLOAD_CTRL_IOBJ");
        if (upload == null) {
            logger.debug("get upload from :{}", webInput.getControllerName());
            String ctrlimpName = (String) webInput.getRequest().getAttribute(CommonUtil.controllerimpclassname);
            if (ctrlimpName != null)
                upload = UploadFactory.getUploadInstance(webInput.getControllerName(), ctrlimpName); // 2007-03-21
            serviceInject(upload);
        }
        if (upload == null) {
            String uploadclass = webInput.getParameter("$upload");
            if (uploadclass == null || uploadclass.trim().length() == 0) {
                throw new ControllerException("upload dealer can't not found!");
            }
            openApiCase = true;
            String uploadclass_ = ControllerFactory.composeClassImpName(webInput.getRequest(), uploadclass);
            logger.debug("uploadclass:{}", uploadclass);
            logger.debug("uploadclass_:{}", uploadclass_);
            upload = UploadFactory.getUploadInstance(uploadclass, uploadclass_);
            serviceInject(upload);
        }
        logger.debug("IUpload:{}", upload);
        long sizeMax = webInput.getParameterAsLong("sizeMax", 0);
        if (sizeMax == 0) {
            sfu.setSizeMax(IUpload.sizeMax);
        } else {
            sfu.setSizeMax(sizeMax);
        }
        int sizeThreshold = webInput.getParameterAsInteger("sizeThreshold", 0);
        if (sizeThreshold == 0) {
            factory.setSizeThreshold(IUpload.sizeThreshold);
        } else {
            factory.setSizeThreshold(sizeThreshold);
        }
        Map<String, String> fieldMap = new HashMap<String, String>();
        List<FileObj> fileList = new ArrayList<FileObj>();
        fileItems = sfu.parseRequest(request);
        Iterator<?> i = fileItems.iterator();
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (fi.isFormField()) {
                fieldMap.put(fi.getFieldName(), fi.getString());
            } else {
                fileList.add(new FileObj(fi));
            }
        }
        fp = new UploadForm(fileList, fieldMap, request, webInput.getResponse());
        View view = upload.processUpload(fp);
        if (view.getViewname() == null || view.getViewname().trim().equals("")) {
            // view.setViewName(AbnormalViewControlerImp.abnormalViewName);
            //
            if (openApiCase) {
                return view;
            }
            UpService us = new UpService(view);
            return us.perform(webInput);
        }
        return view;
    } catch (Exception ex) {
        logger.error("upload", ex);
        throw new ControllerException(WebConst.WEB_EXCEPTION_CODE_UPLOAD, ex);
    } finally {
        if (fileItems != null) {
            fileItems.clear();
        }
        if (fp != null) {
            fp.clear();
        }
        sfu = null;
    }
}

From source file:com.mingsoft.basic.servlet.UploadServlet.java

/**
 * ?post// www  . j av  a2s  . c  o  m
 * @param req HttpServletRequest
 * @param res HttpServletResponse 
 * @throws ServletException ?
 * @throws IOException ?
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    res.setContentType("text/html;charset=utf-8");
    PrintWriter out = res.getWriter();
    String uploadPath = this.getServletContext().getRealPath(File.separator); // 
    String isRename = "";// ???? true:???
    String _tempPath = req.getServletContext().getRealPath(File.separator) + "temp";//
    FileUtil.createFolder(_tempPath);
    File tempPath = new File(_tempPath); // 

    int maxSize = 1000000; // ??,?? 1000000/1024=0.9M
    //String allowedFile = ".jpg,.gif,.png,.zip"; // ?
    String deniedFile = ".exe,.com,.cgi,.asp"; // ??

    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    // ?????
    factory.setSizeThreshold(4096);
    // the location for saving data that is larger than getSizeThreshold()
    // ?SizeThreshold?
    factory.setRepository(tempPath);

    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum size before a FileUploadException will be thrown

    try {
        List fileItems = upload.parseRequest(req);

        Iterator iter = fileItems.iterator();

        // ????
        String regExp = ".+\\\\(.+)$";

        // 
        String[] errorType = deniedFile.split(",");
        Pattern p = Pattern.compile(regExp);
        String outPath = ""; //??
        while (iter.hasNext()) {

            FileItem item = (FileItem) iter.next();
            if (item.getFieldName().equals("uploadPath")) {
                outPath += item.getString();
                uploadPath += outPath;
            } else if (item.getFieldName().equals("isRename")) {
                isRename = item.getString();
            } else if (item.getFieldName().equals("maxSize")) {
                maxSize = Integer.parseInt(item.getString()) * 1048576;
            } else if (item.getFieldName().equals("allowedFile")) {
                //               allowedFile = item.getString();
            } else if (item.getFieldName().equals("deniedFile")) {
                deniedFile = item.getString();
            } else if (!item.isFormField()) { // ???
                String name = item.getName();
                long size = item.getSize();
                if ((name == null || name.equals("")) && size == 0)
                    continue;
                try {
                    // ?? 1000000/1024=0.9M
                    upload.setSizeMax(maxSize);

                    // ?
                    // ?
                    String fileName = System.currentTimeMillis() + name.substring(name.indexOf("."));
                    String savePath = uploadPath + File.separator;
                    FileUtil.createFolder(savePath);
                    // ???
                    if (StringUtil.isBlank(isRename) || Boolean.parseBoolean(isRename)) {
                        savePath += fileName;
                        outPath += fileName;
                    } else {
                        savePath += name;
                        outPath += name;
                    }
                    item.write(new File(savePath));
                    out.print(outPath.trim());
                    logger.debug("upload file ok return path " + outPath);
                    out.flush();
                    out.close();
                } catch (Exception e) {
                    this.logger.debug(e);
                }

            }
        }
    } catch (FileUploadException e) {
        this.logger.debug(e);
    }
}

From source file:edu.ucsd.library.dams.api.DAMSAPIServlet.java

private InputBundle multipartInput(HttpServletRequest req, String objid, String cmpid, String fileid)
        throws IOException, SizeLimitExceededException {
    // process parts
    Map<String, String[]> params = new HashMap<String, String[]>();
    params.putAll(req.getParameterMap());
    InputStream in = null;/*from   www  . j a v  a  2 s  . com*/
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    if (maxUploadSize != -1L) {
        upload.setSizeMax(maxUploadSize);
    }
    List items = null;
    try {
        items = upload.parseRequest(req);
    } catch (SizeLimitExceededException ex) {
        throw ex;
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    for (int i = 0; items != null && i < items.size(); i++) {
        FileItem item = (FileItem) items.get(i);
        // form fields go in parameter map
        if (item.isFormField()) {
            params.put(item.getFieldName(), new String[] { item.getString() });
            log.debug("Parameter: " + item.getFieldName() + " = " + item.getString());
        }
        // file gets opened as an input stream
        else {
            in = item.getInputStream();
            log.debug("File: " + item.getFieldName() + ", " + item.getName());
            params.put("sourceFileName", new String[] { item.getName() });
        }
    }

    // if no file upload found, check for locally-staged file
    if (in == null) {
        in = alternateStream(params, objid, cmpid, fileid);
    }
    return new InputBundle(params, in);
}