Example usage for org.apache.commons.fileupload FileItem isFormField

List of usage examples for org.apache.commons.fileupload FileItem isFormField

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItem isFormField.

Prototype

boolean isFormField();

Source Link

Document

Determines whether or not a FileItem instance represents a simple form field.

Usage

From source file:admin.controller.ServletUpdateFonts.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  w w w .  j  ava2s. com*/
 *
 * @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");
    PrintWriter out = response.getWriter();
    String filePath = null;
    String fileName = null, fieldName = null, uploadPath = null, deletePath = null, file_name_to_delete = "";
    RequestDispatcher request_dispatcher;
    String fontname = null, fontid = null, lookid;

    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {

        uploadPath = AppConstants.BASE_FONT_UPLOAD_PATH;
        deletePath = AppConstants.BASE_FONT_UPLOAD_PATH;
        // 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("fontname")) {
                        fontname = fi.getString();
                    }
                    if (fieldName.equals("fontid")) {
                        fontid = fi.getString();
                        file_name_to_delete = font.getFileName(Integer.parseInt(fontid));
                    }

                } else {
                    fieldName = fi.getFieldName();
                    fileName = fi.getName();
                    if (fileName != "") {

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

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

                        String file_path = uploadPath + File.separator + fileName;
                        String delete_path = deletePath + 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>");
                    }
                }
            }
            font.changeFont(Integer.parseInt(fontid), fontname, fileName);
            response.sendRedirect(request.getContextPath() + "/admin/fontsfamily.jsp");
            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 Updating fonts", ex);
    } finally {
        try {
            out.close();
        } catch (Exception e) {
        }
    }

}

From source file:com.silverpeas.servlets.upload.AjaxFileUploadServlet.java

/**
 * Do the effective upload of files.//from  ww  w. j a v  a  2 s .com
 *
 * @param session the HttpSession
 * @param request the multpart request
 * @throws IOException
 */
@SuppressWarnings("unchecked")
private void doFileUpload(HttpSession session, HttpServletRequest request) throws IOException {
    try {
        session.setAttribute(UPLOAD_ERRORS, "");
        session.setAttribute(UPLOAD_FATAL_ERROR, "");
        List<String> paths = new ArrayList<String>();
        session.setAttribute(FILE_UPLOAD_PATHS, paths);
        FileUploadListener listener = new FileUploadListener(request.getContentLength());
        session.setAttribute(FILE_UPLOAD_STATS, listener.getFileUploadStats());
        FileItemFactory factory = new MonitoringFileItemFactory(listener);
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = (List<FileItem>) upload.parseRequest(request);
        startingToSaveUploadedFile(session);
        String errorMessage = "";
        for (FileItem fileItem : items) {
            if (!fileItem.isFormField() && fileItem.getSize() > 0L) {
                try {
                    String filename = fileItem.getName();
                    if (filename.indexOf('/') >= 0) {
                        filename = filename.substring(filename.lastIndexOf('/') + 1);
                    }
                    if (filename.indexOf('\\') >= 0) {
                        filename = filename.substring(filename.lastIndexOf('\\') + 1);
                    }
                    if (!isInWhiteList(filename)) {
                        errorMessage += "The file " + filename + " is not uploaded!";
                        errorMessage += (StringUtil.isDefined(whiteList)
                                ? " Only " + whiteList.replaceAll(" ", ", ")
                                        + " file types can be uploaded<br/>"
                                : " No allowed file format has been defined for upload<br/>");
                        session.setAttribute(UPLOAD_ERRORS, errorMessage);
                    } else {
                        filename = System.currentTimeMillis() + "-" + filename;
                        File targetDirectory = new File(uploadDir, fileItem.getFieldName());
                        targetDirectory.mkdirs();
                        File uploadedFile = new File(targetDirectory, filename);
                        OutputStream out = null;
                        try {
                            out = new FileOutputStream(uploadedFile);
                            IOUtils.copy(fileItem.getInputStream(), out);
                            paths.add(uploadedFile.getParentFile().getName() + '/' + uploadedFile.getName());
                        } finally {
                            IOUtils.closeQuietly(out);
                        }
                    }
                } finally {
                    fileItem.delete();
                }
            }
        }
    } catch (Exception e) {
        Logger.getLogger(getClass().getSimpleName()).log(Level.WARNING, e.getMessage());
        session.setAttribute(UPLOAD_FATAL_ERROR,
                "Could not process uploaded file. Please see log for details.");
    } finally {
        endingToSaveUploadedFile(session);
    }
}

From source file:ke.co.tawi.babblesms.server.servlet.upload.ContactUpload.java

/**
 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *///from   w  w w .  j a  v  a2 s  . c  om
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    File uploadedFile = null;

    List<String> groupUuids = new LinkedList<>();
    Account account = new Account();

    HttpSession session = request.getSession(false);

    String username = (String) session.getAttribute(SessionConstants.ACCOUNT_SIGN_IN_KEY);

    Element element;
    if ((element = accountsCache.get(username)) != null) {
        account = (Account) element.getObjectValue();
    }

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

    // Set up where the files will be stored on disk
    File repository = new File(System.getProperty("java.io.tmpdir") + File.separator + username);
    FileUtils.forceMkdir(repository);
    factory.setRepository(repository);

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

    // Parse the request              
    try {
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> iter = items.iterator();

        FileItem item;

        while (iter.hasNext()) {
            item = iter.next();

            if (item.isFormField()) {
                // Here we assume only a Group UUID has been submitted as a text field
                groupUuids.add(item.getString());

            } else {
                uploadedFile = processUploadedFile(item);
            }
        } // end 'while (iter.hasNext())'

    } catch (FileUploadException e) {
        logger.error("FileUploadException while getting File Items.");
        logger.error(e);
    }

    // Here we assume that only one file was uploaded
    // First we inspect if it is ok
    String feedback = uploadUtil.inspectContactFile(uploadedFile);
    session.setAttribute(UPLOAD_FEEDBACK, "<p class='error'>" + feedback + "<p>");

    response.sendRedirect("addcontact.jsp");

    // Process the file into the database if it is ok
    if (StringUtils.equals(feedback, UPLOAD_SUCCESS)) {
        uploadUtil.saveContacts(uploadedFile, account, contactDAO, phoneDAO, groupUuids, contactGroupDAO);
    }
}

From source file:com.meikai.common.web.servlet.FCKeditorUploadServlet.java

/**
 * Manage the Upload requests.<br>
 *
 * The servlet accepts commands sent in the following format:<br>
 * simpleUploader?Type=ResourceType<br><br>
 * It store the file (renaming it in case a file with the same name exists) and then return an HTML file
 * with a javascript command in it.//ww w  .ja  v a2s.  c  o m
 *
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (debug)
        System.out.println("--- BEGIN DOPOST ---");

    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");

    PrintWriter out = response.getWriter();
    // edit check user uploader file size
    int contextLength = request.getContentLength();
    int fileSize = (int) (((float) contextLength) / ((float) (1024)));

    String retVal = "0";
    String newName = "";
    String fileUrl = "";
    String errorMessage = "";

    if (fileSize < 30240) {

        String typeStr = request.getParameter("Type");

        String currentPath = "";
        String currentDirPath = getServletContext().getRealPath(currentPath);
        currentPath = request.getContextPath() + currentPath;
        // edit end ++++++++++++++++   
        if (debug)
            System.out.println(currentDirPath);

        if (enabled) {
            DiskFileUpload upload = new DiskFileUpload();
            try {
                List items = upload.parseRequest(request);

                Map fields = new HashMap();

                Iterator iter = items.iterator();
                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();
                    if (item.isFormField())
                        fields.put(item.getFieldName(), item.getString());
                    else
                        fields.put(item.getFieldName(), item);
                }
                FileItem uplFile = (FileItem) fields.get("NewFile");
                String fileNameLong = uplFile.getName();
                fileNameLong = fileNameLong.replace('\\', '/');
                String[] pathParts = fileNameLong.split("/");
                String fileName = pathParts[pathParts.length - 1];

                String nameWithoutExt = FckeditorUtil.getNameWithoutExtension(fileName);
                String ext = FckeditorUtil.getExtension(fileName);
                File pathToSave = new File(currentDirPath, fileName);
                fileUrl = currentPath + "/" + fileName;
                if (FckeditorUtil.extIsAllowed(allowedExtensions, deniedExtensions, typeStr, ext)) {
                    int counter = 1;
                    while (pathToSave.exists()) {
                        newName = nameWithoutExt + "(" + counter + ")" + "." + ext;
                        fileUrl = currentPath + "/" + newName;
                        retVal = "201";
                        pathToSave = new File(currentDirPath, newName);
                        counter++;
                    }
                    uplFile.write(pathToSave);

                    // ?
                    if (logger.isInfoEnabled()) {
                        logger.info("...");
                    }
                } else {
                    retVal = "202";
                    errorMessage = "";
                    if (debug)
                        System.out.println("Invalid file type: " + ext);
                }
            } catch (Exception ex) {
                if (debug)
                    ex.printStackTrace();
                retVal = "203";
            }
        } else {
            retVal = "1";
            errorMessage = "This file uploader is disabled. Please check the WEB-INF/web.xml file";
        }

    } else {
        retVal = "204";
    }
    out.println("<script type=\"text/javascript\">");
    out.println("window.parent.OnUploadCompleted(" + retVal + ",'" + fileUrl + "','" + newName + "','"
            + errorMessage + "');");
    out.println("</script>");
    out.flush();
    out.close();

    if (debug)
        System.out.println("--- END DOPOST ---");

}

From source file:com.wabacus.util.TestFileUploadInterceptor.java

/**
 * ??/??????//from  w w  w. j a v  a2s  .  c om
 */
public boolean beforeDisplayFileUploadPrompt(HttpServletRequest request, List lstFieldItems,
        Map<String, String> mFormAndConfigValues, String failedMessage, PrintWriter out) {
    if (lstFieldItems == null || lstFieldItems.size() == 0)
        return true;
    FileItem fItemTmp;
    StringBuffer fileNamesBuf = new StringBuffer();
    for (int i = 0; i < lstFieldItems.size(); i++) {
        fItemTmp = (FileItem) lstFieldItems.get(i);
        if (fItemTmp.isFormField())
            continue;//?
        fileNamesBuf.append(fItemTmp.getName()).append(";");
    }
    if (fileNamesBuf.charAt(fileNamesBuf.length() - 1) == ';')
        fileNamesBuf.deleteCharAt(fileNamesBuf.length() - 1);
    if (failedMessage != null && !failedMessage.trim().equals("")) {//
        out.println("<h4>??" + fileNamesBuf.toString() + "" + failedMessage
                + "</h4>");
    } else {//?
        out.println("<script language='javascript'>");
        out.println("alert('" + fileNamesBuf.toString() + "?');");

        String inputboxid = mFormAndConfigValues.get("INPUTBOXID");
        if (inputboxid != null && !inputboxid.trim().equals("")) {//?
            String name = mFormAndConfigValues.get("param_name");
            name = name + "[" + fileNamesBuf.toString() + "]";
            out.println("selectOK('" + name + "','name',null,true);");
        }
        out.println("</script>");
    }
    return false;//????
}

From source file:it.fub.jardin.server.Upload.java

@Override
public void doPost(final HttpServletRequest request, final HttpServletResponse response)
/* throws ServletException, IOException */ {
    try {//  w w w.  j av a2s  . co m
        this.dbProperties = new DbProperties();
    } catch (VisibleException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    this.dbConnectionHandler = this.dbProperties.getConnectionHandler();
    try {
        this.dbUtils = new DbUtils(dbProperties, dbConnectionHandler);
    } catch (VisibleException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    this.mailUtility = new MailUtility(dbConnectionHandler.getDbConnectionParameters().getMailSmtpHost(),
            dbConnectionHandler.getDbConnectionParameters().getMailSmtpAuth(),
            dbConnectionHandler.getDbConnectionParameters().getMailSmtpUser(),
            dbConnectionHandler.getDbConnectionParameters().getMailSmtpPass(),
            dbConnectionHandler.getDbConnectionParameters().getMailSmtpSender(),
            dbConnectionHandler.getDbConnectionParameters().getMailSmtpSysadmin());

    subSystem = dbConnectionHandler.getDbConnectionParameters().getSubSystem();
    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

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

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

    String m = null;
    try {

        // Parse the request
        List<?> /* FileItem */ items = upload.parseRequest(request);

        // Process the uploaded items
        Iterator<?> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (item.isFormField()) {
                this.processFormField(item);
            } else {
                m = this.processUploadedFile(item);
            }
        }
        response.setContentType("text/plain");
        response.getWriter().write(m);
    } catch (Exception e) {
        //      Log.warn("Errore durante l'upload del file", e);
    }
}

From source file:eg.agrimarket.controller.SignUpController.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from w ww  . jav  a  2s . com*/
 * @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 {

    CreditDao creditDao = new CreditDaoImpl();

    try {

        boolean creditExist = false;

        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> it = items.iterator();
        HttpSession session = request.getSession(false);
        User user = new User();
        Credit credit = new Credit();
        UserDao userDaoImpl = new UserDaoImpl();
        ArrayList<eg.agrimarket.model.dto.Interest> newInterests = new ArrayList<>();
        while (it.hasNext()) {
            FileItem item = it.next();
            if (!item.isFormField()) {
                byte[] image = item.get();
                if (image != null && image.length != 0) {
                    user.setImage(image);
                }
                System.out.println(user.getImage());
            } else {
                switch (item.getFieldName()) {
                case "name":
                    user.setUserName(item.getString());
                    break;
                case "mail":
                    user.setEmail(item.getString());

                    break;
                case "password":
                    user.setPassword(item.getString());
                    break;
                case "job":
                    user.setJob(item.getString());
                    break;
                case "date":
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                    LocalDate date = LocalDate.parse(item.getString(), formatter);
                    user.setDOB(date);
                    break;
                case "address":
                    user.setAddress(item.getString());
                    break;
                case "credit":
                    user.setCreditNumber(item.getString());
                    credit.setNumber(item.getString());
                    if (creditDao.checkCredit(credit)) {//credit number is exist is 
                        if (!(userDaoImpl.isCreditNumberAssigned(credit))) {
                            creditExist = true;
                            System.out.println("creditExist = true;");
                        } else {

                            creditExist = false;
                            System.out.println("creditExist = falsefalse;");

                        }
                    } else {
                        creditExist = false;

                        System.out.println("creditExist=false;");

                    }
                    break;

                default:
                    eg.agrimarket.model.dto.Interest interest = new eg.agrimarket.model.dto.Interest();
                    interest.setId(Integer.parseInt(item.getString()));
                    interest.setName(item.getFieldName());
                    newInterests.add(interest);
                    System.out.println(item.getFieldName() + " : " + item.getString());
                }
            }
        }

        // check if user exist in Db 
        if (creditExist) {
            user.setInterests(newInterests);
            UserDaoImpl userDao = new UserDaoImpl();

            //
            userDao.signUp(user);
            session.setAttribute("user", user);

            System.out.println(user.getInterests());
            System.out.println(user.getImage());

            response.sendRedirect("index.jsp");
        } else {

            response.sendRedirect("sign_up.jsp");
            System.out.println("user didnt saved");

        }
    } catch (FileUploadException ex) {
        Logger.getLogger(SignUpController.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:controller.CreateProduct.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  w w w  .j a  va 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");
    PrintWriter out = response.getWriter();
    MultipartRequest mr = new MultipartRequest(request,
            "C:/Users/Randy/Documents/NetBeansProjects/Override/web/imagesProducts/");
    try {
        //Clases
        model.business.Producto p = new model.business.Producto();
        model.dal.ProductoDal productoDal = new ProductoDal();

        //Se usa este Request cuando se tiene  enctype="multipart/form-data" (Importar JAR)

        /*FileItemFactory es una interfaz para crear FileItem*/
        FileItemFactory file_factory = new DiskFileItemFactory();

        /*ServletFileUpload esta clase convierte los input file a FileItem*/
        ServletFileUpload servlet_up = new ServletFileUpload(file_factory);
        /*sacando los FileItem del ServletFileUpload en una lista */
        List items = servlet_up.parseRequest(request);

        for (int i = 0; i < items.size(); i++) {
            /*FileItem representa un archivo en memoria que puede ser pasado al disco duro*/
            FileItem item = (FileItem) items.get(i);
            /*item.isFormField() false=input file; true=text field*/
            if (!item.isFormField()) {
                /*cual sera la ruta al archivo en el servidor*/

                File archivo_server = new File(
                        "C:/Users/Randy/Documents/NetBeansProjects/Override/web/imagesProducts/"
                                + item.getName());
                /*y lo escribimos en el servido*/
                item.write(archivo_server);
            }
        }

        //Set
        p.setIdProducto(Integer.parseInt(mr.getParameter("txt_id_producto")));
        p.setNombreProducto(mr.getParameter("txt_nombre_producto"));
        p.setPrecioUnitario(Integer.parseInt(mr.getParameter("txt_precio")));
        p.setStock(Integer.parseInt(mr.getParameter("txt_stock")));
        p.setDescripcion(mr.getParameter("txt_descripcion"));
        p.getTipoProducto().setIdTipoProducto(Integer.parseInt(mr.getParameter("ddl_lista_tipo_producto")));
        p.getMarca().setIdMarca(Integer.parseInt(mr.getParameter("ddl_marca_producto")));
        //Recoge el NOMBRE del file
        p.setUrlFoto(mr.getFilesystemName("file"));
        p.setEstado(Integer.parseInt(mr.getParameter("rbtn_estado")));

        //Registro BD
        int resultado = productoDal.insertProduct(p);
        switch (resultado) {
        case 1:
            //out.print("Registro OK");
            //Pagina Redirrecion
            request.getRequestDispatcher("redirect_index_intranet_producto_creado.jsp").forward(request,
                    response);
            break;
        case 1062:
            //out.print("Producto Existente");
            //Pagina Redirrecion
            request.getRequestDispatcher("redirect_index_intranet_error_producto_existente.jsp")
                    .forward(request, response);
            break;
        default:
            //Error genrico
            request.getRequestDispatcher("redirect_index_intranet_error.jsp").forward(request, response);
            //out.print("Error : "+ productoDal.insertProduct(p));
            //Pagina Redirrecion
            //request.getRequestDispatcher("pagina.jsp").forward(request, response);
            break;
        }

    } catch (Exception e) {
        //Error genrico
        request.getRequestDispatcher("redirect_index_intranet_error.jsp").forward(request, response);
        //out.print("error : " + e.getMessage());
    }
}

From source file:admin.controller.ServletEditCategories.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// ww  w. j ava2  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
 */
@Override
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();

    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {

        upload_path = AppConstants.ORG_CATEGORIES_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(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
                    field_name = fi.getFieldName();
                    if (field_name.equals("category_name")) {
                        category_name = fi.getString();
                    }
                    if (field_name.equals("category_id")) {
                        category_id = fi.getString();
                    }
                    if (field_name.equals("organization")) {
                        organization_id = fi.getString();
                        upload_path = upload_path + File.separator + organization_id;
                    }

                } else {
                    field_name = fi.getFieldName();
                    file_name = fi.getName();

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

                        //                            int inStr = file_name.indexOf(".");
                        //                            String Str = file_name.substring(0, inStr);
                        //
                        //                            file_name = category_name + "_" + Str + ".jpeg";
                        file_name = category_name + "_" + file_name;
                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();

                        String filePath = upload_path + File.separator + file_name;
                        File storeFile = new File(filePath);

                        fi.write(storeFile);

                        out.println("Uploaded Filename: " + filePath + "<br>");
                    }
                }
            }
            categories.editCategories(Integer.parseInt(category_id), Integer.parseInt(organization_id),
                    category_name, file_name);
            response.sendRedirect(request.getContextPath() + "/admin/categories.jsp");
            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 categories", ex);
    } finally {
        try {
            out.close();
        } catch (Exception e) {
        }
    }

}

From source file:admin.controller.ServletAddCategories.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// w  ww  .  ja v a2  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);
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {

        String uploadPath = AppConstants.ORG_CATEGORIES_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(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
                    field_name = fi.getFieldName();
                    if (field_name.equals("category_name")) {
                        category_name = fi.getString();
                    }
                    if (field_name.equals("organization")) {
                        organization_id = fi.getString();
                        uploadPath = uploadPath + File.separator + organization_id;
                    }

                } else {

                    field_name = fi.getFieldName();
                    file_name = fi.getName();
                    if (file_name != "") {
                        check = categories.checkAvailability(category_name, Integer.parseInt(organization_id));
                        if (check == false) {
                            File uploadDir = new File(uploadPath);
                            if (!uploadDir.exists()) {
                                uploadDir.mkdirs();
                            }

                            //we need to save file name directly
                            //                                int inStr = file_name.indexOf(".");
                            //                                String Str = file_name.substring(0, inStr);
                            //                                file_name = category_name + "_" + Str + ".jpeg";

                            file_name = category_name + "_" + file_name;
                            boolean isInMemory = fi.isInMemory();
                            long sizeInBytes = fi.getSize();

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

                            fi.write(storeFile);
                            categories.addCategories(Integer.parseInt(organization_id), category_name,
                                    file_name);

                            out.println("Uploaded Filename: " + filePath + "<br>");
                            response.sendRedirect(request.getContextPath() + "/admin/categories.jsp");
                        } else {
                            response.sendRedirect(
                                    request.getContextPath() + "/admin/categories.jsp?exist=exist");
                        }
                    }
                }
            }
            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 adding categories", ex);
    } finally {
        out.close();
    }
}