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:admin.controller.ServletChangeLooks.java

/**
  * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
  * methods./*from  w ww .j av 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
  */
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.processRequest(request, response);
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    String filePath = "";
    String fileName, fieldName, uploadPath, deletePath, file_name_to_delete = "", uploadPath1;
    Looks look;
    RequestDispatcher request_dispatcher;
    String lookname = "", lookid = "";
    Integer organization = 0;
    look = new Looks();
    boolean check = false;

    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();

            out.println("<html>");
            out.println("<head>");
            out.println("<title>JSP File upload</title>");
            out.println("</head>");
            out.println("<body>");
            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (fi.isFormField()) {
                    // Get the uploaded file parameters
                    fieldName = fi.getFieldName();
                    if (fieldName.equals("lookname")) {
                        lookname = fi.getString();
                    }
                    if (fieldName.equals("lookid")) {
                        lookid = fi.getString();
                    }
                    if (fieldName.equals("organization")) {
                        organization = Integer.parseInt(fi.getString());
                    }
                    file_name_to_delete = look.getFileName(Integer.parseInt(lookid));
                } else {

                    check = look.checkAvailabilities(Integer.parseInt(lookid), lookname, organization);

                    if (check == false) {

                        fieldName = fi.getFieldName();
                        fileName = fi.getName();

                        File uploadDir = new File(AppConstants.LOOK_IMAGES_HOME);

                        if (!uploadDir.exists()) {
                            uploadDir.mkdirs();
                        }

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

                        String file_path = AppConstants.LOOK_IMAGES_HOME + File.separator + fileName;
                        String delete_path = AppConstants.LOOK_IMAGES_HOME + File.separator
                                + file_name_to_delete;
                        File deleteFile = new File(delete_path);
                        deleteFile.delete();
                        File storeFile = new File(file_path);
                        fi.write(storeFile);
                        out.println("Uploaded Filename: " + filePath + "<br>");
                        look.changeLooks(Integer.parseInt(lookid), lookname, fileName, organization);
                        response.sendRedirect(request.getContextPath() + "/admin/looks.jsp");
                    } else {
                        response.sendRedirect(
                                request.getContextPath() + "/admin/editlook.jsp?exist=exist&look_id=" + lookid
                                        + "&look_name=" + lookname + "&organization_id=" + organization
                                        + "&image_file_name=" + file_name_to_delete);
                    }
                }
            }
            out.println("</body>");
            out.println("</html>");
        } 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>");
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Exception while editing the looks", ex);
    } finally {
        out.close();
    }

}

From source file:com.bluelotussoftware.apache.commons.fileupload.example.FileUploadServlet.java

/**
 * Processes requests for both HTTP/*from  w  w w.j  a  va 2 s.  c om*/
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @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");
    boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
    log("isMultipartContent: " + isMultiPart);
    log("Content-Type: " + request.getContentType());
    if (isMultiPart) {

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

        /*
         * Set the file size limit in bytes. This should be set as an
         * initialization parameter
         */
        diskFileItemFactory.setSizeThreshold(1024 * 1024 * 10); //10MB.

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

        // Parse the request
        List items = null;
        try {
            items = upload.parseRequest(request);
        } catch (FileUploadException ex) {
            log("Could not parse request", ex);
        }

        PrintWriter out = response.getWriter();
        out.print("<html><head><title>SUCCESS</title></head><body><h1>DONE!</h1>");

        ListIterator li = items.listIterator();
        while (li.hasNext()) {
            FileItem fileItem = (FileItem) li.next();
            if (fileItem.isFormField()) {
                processFormField(fileItem);
            } else {
                out.append(processUploadedFile(fileItem));
            }
        }
        out.print("</body></html>");
        out.flush();
        out.close();

    }
}

From source file:com.jkingii.web.files.upload.java

/**
 * Processes requests for both HTTP/*  w  ww  . j  a v a 2  s. c  o m*/
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @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 {
    // Check that we have a file upload request
    isMultipart = ServletFileUpload.isMultipartContent(request);
    FileDataBase fdb = null;
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
        CSession cSession = (CSession) request.getSession().getAttribute("cSession");

        if (!isMultipart) {
            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>");
            return;
        }

        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(tempDir));

        // 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);

        // Se verifica si el usuario tiene permisos de escritura.
        ColumnasPermisos permiso = checkPermisos(request, fileItems, out);
        if (permiso == null) {
            return;
        }

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

        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            MessageDigest md5 = MessageDigest.getInstance("MD5");

            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                logger.info("Prosess Request: obteniendo session: [" + cSession + "] jsessionid = ["
                        + request.getSession().getId() + "]", this);
                fdb = new FileDataBase(GenKey.newKey(), cSession.getAccessInfo().getEmpresa(),
                        cSession.getAccessInfo().getUserInfo(), new Date().getTime(), fi.getName(),
                        new MimeType().factory().getMime(fi.getName(), fi.get()), fi.get(),
                        Hexadecimal.getHex(md5.digest(fi.get())), fi.getSize(), permiso);
                fileDataBaseFacade.create(fdb);
            }
        }
        ResponseConfig config = new ResponseConfig();
        config.setTimeZone(cSession.getAccessInfo().getTimeZone());
        out.println(fdb.toJson(config));
    } catch (FileUploadException | NoSuchAlgorithmException e) {
        logger.error("Error cargando el fichero en el servidor, " + "Exception: {}", e.getMessage());
    } catch (UnknownColumnException e) {
        logger.error("Imposible la columna para el link debe existir referer[{}], " + "p[{}]",
                request.getHeader("referer"), request.getParameter(PERMISO_FIELD));
        logger.debug("referrer: " + request.getHeader("referrer"));
    } finally {
        out.close();
    }
}

From source file:com.javaweb.controller.SuaTinTucServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request/*from  w w  w.j  a  va 2 s. c o m*/
 * @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, ParseException {
    response.setContentType("text/html;charset=UTF-8");
    request.setCharacterEncoding("UTF-8");

    //response.setCharacterEncoding("UTF-8");
    HttpSession session = request.getSession();
    String TieuDe = "", NoiDung = "", ngaydang = "", GhiChu = "", fileName = "";
    int idloaitin = 0, idTK = 0, idtt = 0;

    TintucService tintucservice = new TintucService();

    //File upload
    String folderupload = getServletContext().getInitParameter("file-upload");
    String rootPath = getServletContext().getRealPath("/");
    filePath = rootPath + folderupload;
    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();

    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:\\Windows\\Temp\\"));

    // 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();
                fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();

                //change file name
                fileName = FileService.ChangeFileName(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));
                }
                fi.write(file);
                //                    out.println("Uploaded Filename: " + fileName + "<br>");
            }

            if (fi.isFormField()) {
                if (fi.getFieldName().equalsIgnoreCase("TieuDe")) {
                    TieuDe = fi.getString("UTF-8");
                } else if (fi.getFieldName().equalsIgnoreCase("NoiDung")) {
                    NoiDung = fi.getString("UTF-8");
                } else if (fi.getFieldName().equalsIgnoreCase("NgayDang")) {
                    ngaydang = fi.getString("UTF-8");
                } else if (fi.getFieldName().equalsIgnoreCase("GhiChu")) {
                    GhiChu = fi.getString("UTF-8");
                } else if (fi.getFieldName().equalsIgnoreCase("loaitin")) {
                    idloaitin = Integer.parseInt(fi.getString("UTF-8"));
                } else if (fi.getFieldName().equalsIgnoreCase("idtaikhoan")) {
                    idTK = Integer.parseInt(fi.getString("UTF-8"));
                } else if (fi.getFieldName().equalsIgnoreCase("idtt")) {
                    idtt = Integer.parseInt(fi.getString("UTF-8"));
                }
            }
        }

    } catch (Exception ex) {
        System.out.println(ex);
    }

    Date NgayDang = new SimpleDateFormat("yyyy-MM-dd").parse(ngaydang);

    Tintuc tt = tintucservice.GetTintucID(idtt);

    tt.setIdTaiKhoan(idTK);
    tt.setTieuDe(TieuDe);
    tt.setNoiDung(NoiDung);
    tt.setNgayDang(NgayDang);
    tt.setGhiChu(GhiChu);
    if (!fileName.equals("")) {
        if (tt.getImgLink() != null) {
            if (!tt.getImgLink().equals(fileName)) {
                tt.setImgLink(fileName);
            }
        } else {
            tt.setImgLink(fileName);
        }
    }

    boolean rs = tintucservice.InsertTintuc(tt);
    if (rs) {
        session.setAttribute("kiemtra", "1");
        response.sendRedirect("SuaTinTuc.jsp?idTintuc=" + idtt);
    } else {
        session.setAttribute("kiemtra", "0");
        response.sendRedirect("SuaTinTuc.jsp?idTintuc=" + idtt);
    }

    //        try (PrintWriter out = response.getWriter()) {
    //            /* TODO output your page here. You may use following sample code. */
    //            out.println("<!DOCTYPE html>");
    //            out.println("<html>");
    //            out.println("<head>");
    //            out.println("<title>Servlet SuaTinTucServlet</title>");            
    //            out.println("</head>");
    //            out.println("<body>");
    //            out.println("<h1>Servlet SuaTinTucServlet at " + request.getContextPath() + "</h1>");
    //            out.println("</body>");
    //            out.println("</html>");
    //        }
}

From source file:controller.uploadProductController.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from  www. j a v  a 2s.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 {
    HttpSession session = request.getSession(true);
    String userPath = request.getServletPath();
    if (userPath.equals("/uploadProduct")) {
        boolean success = true;
        // 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().getInitParameter("upload.location");
        //creates a HashMap of all inputs
        HashMap hashMap = new HashMap();
        String productId = UUID.randomUUID().toString();
        try {
            @SuppressWarnings("unchecked")
            List<FileItem> formItems = upload.parseRequest(request);
            for (FileItem item : formItems) {
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    File file = new File(item.getName());
                    File file2 = new File(productId + ".jpg");
                    String filePath = uploadPath + File.separator + file.getName();
                    // saves the file on disk
                    File storeFile = new File(filePath);
                    item.write(storeFile);
                    File rename = new File(filePath);
                    boolean flag = rename.renameTo(file2);
                } else {
                    hashMap.put(item.getFieldName(), item.getString());
                }
            }
        } catch (FileUploadException ex) {
            Logger.getLogger(uploadProductController.class.getName()).log(Level.SEVERE, null, ex);
            request.setAttribute("error", true);
            request.setAttribute("errorMessage", ex.getMessage());
            success = false;
        } catch (Exception ex) {
            Logger.getLogger(uploadProductController.class.getName()).log(Level.SEVERE, null, ex);
            request.setAttribute("error", true);
            request.setAttribute("errorMessage", ex.getMessage());
            success = false;
        }
        String owner = (String) session.getAttribute("customerEmail");
        if (owner == null) {
            owner = "shop";
        }

        String pName = hashMap.get("pName").toString();
        String mNo = hashMap.get("mNo").toString();
        String brand = hashMap.get("brand").toString();
        String description = hashMap.get("description").toString();
        String quantity = hashMap.get("quantity").toString();
        String price = hashMap.get("price").toString();
        String addInfo = hashMap.get("addInfo").toString();
        int categoryId = Integer.parseInt(hashMap.get("category").toString());

        ProductDAO productDAO = new ProductDAOImpl();
        Product product;

        try {
            double priceDouble = Double.parseDouble(price);
            int quantityInt = Integer.parseInt(quantity);
            Category category = (new CategoryDAOImpl()).getCategoryFromID(categoryId);
            if (owner.equals("shop")) {
                product = new Product(productId, pName, mNo, category, quantityInt, priceDouble, brand,
                        description, addInfo, true, true, owner);
            } else {
                product = new Product(productId, pName, mNo, category, quantityInt, priceDouble, brand,
                        description, addInfo, false, false, owner);
            }

            if (!(productDAO.addProduct(product, category.getName()))) {
                throw new Exception("update unsuccessful");
            }
        } catch (Exception e) {
            request.setAttribute("error", true);
            request.setAttribute("errorMessage", e.getMessage());
            success = false;
        }

        request.setAttribute("pName", pName);
        request.setAttribute("mNo", mNo);
        request.setAttribute("brand", brand);
        request.setAttribute("description", description);
        request.setAttribute("quantity", quantity);
        request.setAttribute("price", price);
        request.setAttribute("addInfo", addInfo);
        request.setAttribute("categoryId", categoryId);
        request.setAttribute("success", success);
        if (success == true) {
            request.setAttribute("error", false);
            request.setAttribute("errorMessage", null);
        }
        String url;
        if (owner.equals("shop")) {
            url = "/WEB-INF/view/adminAddProducts.jsp";
        } else {
            url = "/WEB-INF/view/clientSideView/addRecycleProduct.jsp";
        }
        try {
            request.getRequestDispatcher(url).forward(request, response);
        } catch (ServletException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }

}

From source file:gov.nih.nci.evs.browser.servlet.UploadServlet.java

/**
 * Process the specified HTTP request, and create the corresponding HTTP
 * response (or forward to another web component that will create it).
 *
 * @param request The HTTP request we are processing
 * @param response The HTTP response we are creating
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet exception occurs
 *//*from w  w w.  j ava2  s .c  om*/

public void execute(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    // Determine request by attributes
    String action = (String) request.getParameter("action");
    String type = (String) request.getParameter("type");

    System.out.println("(*) UploadServlet ...action " + action);
    if (action == null) {
        action = "upload_data";
    }

    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
    /*
     *Set the size threshold, above which content will be stored on disk.
     */
    fileItemFactory.setSizeThreshold(1 * 1024 * 1024); //1 MB
    /*
     * Set the temporary directory to store the uploaded files of size above threshold.
     */
    //fileItemFactory.setRepository(tmpDir);

    ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
    try {
        /*
         * Parse the request
         */
        List items = uploadHandler.parseRequest(request);
        Iterator itr = items.iterator();
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            /*
             * Handle Form Fields.
             */
            if (item.isFormField()) {
                System.out.println("File Name = " + item.getFieldName() + ", Value = " + item.getString());
                //String s = convertStreamToString(item.getInputStream(), item.getSize());
                //System.out.println(s);

            } else {
                //Handle Uploaded files.
                System.out.println("Field Name = " + item.getFieldName() + ", File Name = " + item.getName()
                        + ", Content type = " + item.getContentType() + ", File Size = " + item.getSize());

                String s = convertStreamToString(item.getInputStream(), item.getSize());
                //System.out.println(s);

                request.getSession().setAttribute("action", action);

                if (action.compareTo("upload_data") == 0) {
                    request.getSession().setAttribute("codes", s);
                } else {
                    Mapping mapping = new Mapping().toMapping(s);

                    System.out.println("Mapping " + mapping.getMappingName() + " uploaded.");
                    System.out.println("Mapping version: " + mapping.getMappingVersion());

                    MappingObject obj = mapping.toMappingObject();
                    HashMap mappings = (HashMap) request.getSession().getAttribute("mappings");
                    if (mappings == null) {
                        mappings = new HashMap();
                    }
                    mappings.put(obj.getKey(), obj);
                    request.getSession().setAttribute("mappings", mappings);
                }
            }
        }
    } catch (FileUploadException ex) {
        log("Error encountered while parsing the request", ex);
    } catch (Exception ex) {
        log("Error encountered while uploading file", ex);
    }

    //long ms = System.currentTimeMillis();

    if (action.compareTo("upload_data") == 0) {
        if (type.compareTo("codingscheme") == 0) {
            response.sendRedirect(
                    response.encodeRedirectURL(request.getContextPath() + "/pages/codingscheme_data.jsf"));
        } else if (type.compareTo("ncimeta") == 0) {
            response.sendRedirect(
                    response.encodeRedirectURL(request.getContextPath() + "/pages/ncimeta_data.jsf"));
        } else if (type.compareTo("valueset") == 0) {
            response.sendRedirect(
                    response.encodeRedirectURL(request.getContextPath() + "/pages/valueset_data.jsf"));
        }
    } else {
        response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/pages/home.jsf"));
    }

}

From source file:com.glaf.base.utils.upload.FileUploadBackGroundServlet.java

/**
 * ?//w  w  w . jav a2  s  .c  o  m
 */
private void processFileUpload(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String serviceKey = request.getParameter("serviceKey");
    if (serviceKey == null) {
        serviceKey = "global";
    }

    int maxUploadSize = conf.getInt(serviceKey + ".maxUploadSize", 0);
    if (maxUploadSize == 0) {
        maxUploadSize = conf.getInt("upload.maxUploadSize", 10);// 10MB
    }
    maxUploadSize = maxUploadSize * FileUtils.MB_SIZE;
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // ?
    factory.setSizeThreshold(204800);
    File tempDir = new File(getUploadDir() + "/temp");
    if (!tempDir.exists()) {
        tempDir.mkdir();
    }

    // ?
    factory.setRepository(tempDir);
    ServletFileUpload upload = new ServletFileUpload(factory);
    // ?
    upload.setFileSizeMax(maxUploadSize);
    // request
    upload.setSizeMax(maxUploadSize);
    upload.setProgressListener(new FileUploadListener(request));
    upload.setHeaderEncoding("UTF-8");
    // ???FileUploadStatus Bean
    FileMgmtFactory.saveStatusBean(request, initStatusBean(request));

    try {
        List<?> items = upload.parseRequest(request);
        // url
        for (int i = 0; i < items.size(); i++) {
            FileItem item = (FileItem) items.get(i);
            if (item.isFormField()) {

                break;
            }
        }
        // 
        String uploadDir = com.glaf.base.utils.StringUtil.createDir(getUploadDir());
        // ?
        for (int i = 0; i < items.size(); i++) {
            FileItem item = (FileItem) items.get(i);
            // ?
            if (FileMgmtFactory.getStatusBean(request).getCancel()) {
                deleteUploadedFile(request);
                break;
            } else if (!item.isFormField() && item.getName().length() > 0) {
                logger.debug("" + item.getName());
                // ?
                String fileId = UUID32.getUUID();
                String path = uploadDir + FileUtils.sp + fileId;
                File uploadedFile = new File(new File(getUploadDir(), uploadDir), fileId);
                item.write(uploadedFile);
                // 
                FileUploadStatus satusBean = FileMgmtFactory.getStatusBean(request);
                FileInfo fileInfo = new FileInfo();
                fileInfo.setCreateDate(new Date());
                fileInfo.setFileId(fileId);
                fileInfo.setFile(uploadedFile);
                fileInfo.setFilename(FileUtils.getFilename(item.getName()));
                fileInfo.setSize(item.getSize());
                fileInfo.setPath(path);
                satusBean.getUploadFileUrlList().add(fileInfo);
                FileMgmtFactory.saveStatusBean(request, satusBean);
                Thread.sleep(500);
            }
        }

    } catch (FileUploadException ex) {
        uploadExceptionHandle(request, "?:" + ex.getMessage());
    } catch (Exception ex) {
        uploadExceptionHandle(request, "??:" + ex.getMessage());
    }
    String forwardURL = request.getParameter("forwardURL");
    if (StringUtils.isEmpty(forwardURL)) {
        forwardURL = "/others/attachment.do?method=showResult";
    }
    request.getRequestDispatcher(forwardURL).forward(request, response);
}

From source file:edu.emory.cci.aiw.cvrg.eureka.servlet.JobSubmitServlet.java

private Long submitJob(HttpServletRequest request, Principal principal)
        throws FileUploadException, IOException, ClientException, ParseException {

    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();

    /*/*from ww  w .  j av a2 s .  c  o  m*/
     *Set the size threshold, above which content will be stored on disk.
     */
    fileItemFactory.setSizeThreshold(5 * 1024 * 1024); //5 MB
    /*
     * Set the temporary directory to store the uploaded files of size above threshold.
     */
    fileItemFactory.setRepository(this.tmpDir);

    ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
    /*
     * Parse the request
     */
    List items = uploadHandler.parseRequest(request);
    Properties fields = new Properties();
    for (Iterator itr = items.iterator(); itr.hasNext();) {
        FileItem item = (FileItem) itr.next();
        /*
         * Handle Form Fields.
         */
        if (item.isFormField()) {
            fields.setProperty(item.getFieldName(), item.getString());
        }
    }

    JobSpec jobSpec = MAPPER.readValue(fields.getProperty("jobSpec"), JobSpec.class);

    for (Iterator itr = items.iterator(); itr.hasNext();) {
        FileItem item = (FileItem) itr.next();
        if (!item.isFormField()) {
            //Handle Uploaded files.
            log("Spreadsheet upload for user " + principal.getName() + ": Field Name = " + item.getFieldName()
                    + ", File Name = " + item.getName() + ", Content type = " + item.getContentType()
                    + ", File Size = " + item.getSize());
            if (item.getSize() > 0) {
                InputStream is = item.getInputStream();
                try {
                    this.servicesClient.upload(FilenameUtils.getName(item.getName()),
                            jobSpec.getSourceConfigId(), item.getFieldName(), is);
                    log("File '" + item.getName() + "' uploaded successfully");
                } finally {
                    if (is != null) {
                        try {
                            is.close();
                        } catch (IOException ignore) {
                        }
                    }
                }
            } else {
                log("File '" + item.getName() + "' ignored because it was zero length");
            }
        }
    }

    URI uri = this.servicesClient.submitJob(jobSpec);
    String uriStr = uri.toString();
    Long jobId = Long.valueOf(uriStr.substring(uriStr.lastIndexOf("/") + 1));
    log("Job " + jobId + " submitted for user " + principal.getName());
    return jobId;
}

From source file:com.pureinfo.tgirls.servlet.TestServlet.java

private File uploadFile(HttpServletRequest request) throws Exception {
    // ,??ServletFileUpload
    DiskFileItemFactory dfif = new DiskFileItemFactory();
    dfif.setSizeThreshold(4096);// ?,4K.
    String tempfilepath = FileFactory.getInstance().lookupPathConfigByFlag("UP", true).getLocalPath();
    dfif.setRepository(new File(tempfilepath));// 

    // //from  w ww. ja  va2  s  .com
    ServletFileUpload sfu = new ServletFileUpload(dfif);
    sfu.setHeaderEncoding("utf-8");
    // 
    //sfu.setSizeMax(MAX_SIZE_5M);

    // PrintWriter out = response.getWriter();
    // request  
    List fileList = null;
    try {
        fileList = sfu.parseRequest(request);
    } catch (FileUploadException e) {// ?
        logger.error("FileUploadException", e);
        if (e instanceof SizeLimitExceededException) {
            throw new Exception("?:" + MAX_SIZE_5M / 1024 + "K");
        }
    }
    // 
    if (fileList == null || fileList.size() == 0) {
        throw new Exception("");
    }
    // 
    Iterator fileItr = fileList.iterator();
    // ?
    while (fileItr.hasNext()) {
        FileItem fileItem = null;
        String path = null;
        long size = 0;
        // ?
        fileItem = (FileItem) fileItr.next();
        // ?form?(<input type="text" />)

        if (fileItem == null || fileItem.isFormField()) {
            continue;
        }
        // 
        path = fileItem.getName();

        logger.debug("path:" + path);

        // ?
        size = fileItem.getSize();
        if ("".equals(path) || size == 0) {
            throw new Exception("");
        }

        // ??
        String t_name = path.substring(path.lastIndexOf("\\") + 1);
        // ??(????)
        String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1);

        logger.debug("the file ext name:" + t_ext);

        // ???
        int allowFlag = 0;
        int allowedExtCount = allowedExt.length;
        for (; allowFlag < allowedExtCount; allowFlag++) {
            if (allowedExt[allowFlag].equals(t_ext.toLowerCase()))
                break;
        }
        if (allowFlag == allowedExtCount) {
            String error = ":";
            for (allowFlag = 0; allowFlag < allowedExtCount; allowFlag++)
                error += "*." + allowedExt[allowFlag] + "  ";
            throw new Exception(error);
        }

        // ?
        String u_name = FileFactory.getInstance().getNextFileName("UP", t_ext, true);
        File temp = new File(u_name);

        int[] imgSize = getimgSize(fileItem);
        if ((imgSize[0] > 0 && imgSize[0] < 300) || (imgSize[1] > 0 && imgSize[1] < 300)) {
            throw new Exception("300x300");
        }

        logger.debug("to write file:" + temp);

        // ?
        fileItem.write(temp);

        temp = resizePic(temp);
        return temp;

    }

    throw new Exception("");

}

From source file:net.formio.upload.MultipartRequestPreprocessor.java

/**
 * Wrapper which preprocesses multipart request.
 * @param parser multipart request parser
 * @param defaultEncoding header and request parameter encoding 
 * @param tempDir temporary directory to store files bigger than specified size threshold
 * @param sizeThreshold max size of file (in bytes) that is loaded into the memory and not temporarily stored to disk
 * @param totalSizeMax maximum allowed size of the whole request in bytes
 * @param singleFileSizeMax maximum allowed size of a single uploaded file
 */// ww w. ja  va 2 s.c  o m
public MultipartRequestPreprocessor(MultipartRequestParser parser, String defaultEncoding, File tempDir,
        int sizeThreshold, long totalSizeMax, long singleFileSizeMax) {
    this.defaultEncoding = defaultEncoding;
    final DiskFileItemFactory fif = new DiskFileItemFactory();
    if (tempDir != null) {
        fif.setRepository(tempDir);
    }
    if (sizeThreshold > 0) {
        fif.setSizeThreshold(sizeThreshold);
    }
    try {
        List<FileItem> fileItems = parser.parseFileItems(fif, singleFileSizeMax, totalSizeMax, defaultEncoding);
        convertToMaps(fileItems);
    } finally {
        this.error = parser.getError();
    }
}