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

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

Introduction

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

Prototype

String getFieldName();

Source Link

Document

Returns the name of the field in the multipart form corresponding to this file item.

Usage

From source file:com.niconico.mylasta.direction.sponsor.NiconicoMultipartRequestHandler.java

protected void addTextParameter(HttpServletRequest request, FileItem item) {
    final String name = item.getFieldName();
    final String encoding = request.getCharacterEncoding();
    String value = null;//w w  w  . j a v a2s . c o m
    boolean haveValue = false;
    if (encoding != null) {
        try {
            value = item.getString(encoding);
            haveValue = true;
        } catch (Exception e) {
        }
    }
    if (!haveValue) {
        try {
            value = item.getString("ISO-8859-1");
        } catch (java.io.UnsupportedEncodingException uee) {
            value = item.getString();
        }
        haveValue = true;
    }
    if (request instanceof MultipartRequestWrapper) {
        final MultipartRequestWrapper wrapper = (MultipartRequestWrapper) request;
        wrapper.setParameter(name, value);
    }
    final String[] oldArray = elementsText.get(name);
    final String[] newArray;
    if (oldArray != null) {
        newArray = new String[oldArray.length + 1];
        System.arraycopy(oldArray, 0, newArray, 0, oldArray.length);
        newArray[oldArray.length] = value;
    } else {
        newArray = new String[] { value };
    }
    elementsText.put(name, newArray);
    elementsAll.put(name, newArray);
}

From source file:gov.nih.nci.caadapter.ws.AddNewScenario.java

/** **********************************************************
 *  doPost()/*from   www  . ja  v a 2 s.  co m*/
 ************************************************************ */
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    try {
        /* disable security for caAdatper 4.3 release 03-31-2009
         HttpSession session = req.getSession(false);
                
          if(session==null)
          {
          res.sendRedirect("/caAdapterWS/login.do");
          return;
          }
                
          String user = (String) session.getAttribute("userid");
          System.out.println(user);
          AbstractSecurityDAO abstractDao= DAOFactory.getDAO();
          SecurityAccessIF getSecurityAccess = abstractDao.getSecurityAccess();
          Permissions perm = getSecurityAccess.getUserObjectPermssions(user, 1);
          System.out.println(perm);
          if (!perm.getCreate()){
          System.out.println("No create Permission for user" + user);
          res.sendRedirect("/caAdapterWS/permissionmsg.do");
          return;
          }
          */
        String name = "EMPTY";

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

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

        // Parse the request
        List /* FileItem */ items = upload.parseRequest(req);

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

            if (item.isFormField()) {
                if (item.getFieldName().equals("MSName")) {
                    MSName = item.getString();
                    path = System.getProperty("gov.nih.nci.caadapter.path");
                    if (path == null)
                        path = ScenarioUtil.SCENARIO_HOME;
                    File scnHome = new File(path);
                    if (!scnHome.exists())
                        scnHome.mkdir();
                    path = path + "/";
                    System.out.println(path);
                    boolean exists = (new File(path + MSName)).exists();
                    if (exists) {
                        System.out.println("Scenario exists, overwriting ... ...");
                        String errMsg = "Scenario exists, not able to save:" + MSName;
                        req.setAttribute("rtnMessage", errMsg);
                        res.sendRedirect("/caAdapterWS/errormsg.do");
                        return;
                    } else {
                        boolean success = (new File(path + MSName)).mkdir();
                        if (!success) {
                            System.out.println("New scenario, Creating ... ...");
                        }
                    }

                }
            } else {
                System.out.println(item.getFieldName());
                name = item.getFieldName();

                String filePath = item.getName();
                String fileName = extractOriginalFileName(filePath);
                System.out.println("AddNewScenario.doPost()..original file Name:" + fileName);
                if (fileName == null || fileName.equals(""))
                    continue;
                String uploadedFilePath = path + MSName + "/" + fileName;
                System.out.println("AddNewScenario.doPost()...write data to file:" + uploadedFilePath);
                File uploadedFile = new File(uploadedFilePath);
                if (name.equals("mappingFileName")) {
                    String uploadedMapBak = uploadedFilePath + ".bak";
                    //write bak of Mapping file
                    item.write(new File(uploadedMapBak));
                    updateMapping(uploadedMapBak);
                } else
                    item.write(uploadedFile);
            }
        }
        ScenarioUtil.addNewScenarioRegistration(MSName);
        res.sendRedirect("/caAdapterWS/success.do");

    } catch (NullPointerException ne) {
        System.out.println("Error in doPost: " + ne);
        req.setAttribute("rtnMessage", ne.getMessage());
        res.sendRedirect("/caAdapterWS/errormsg.do");
    } catch (Exception e) {
        System.out.println("Error in doPost: " + e);
        req.setAttribute("rtnMessage", e.getMessage());
        res.sendRedirect("/caAdapterWS/error.do");
    }
}

From source file:com.aquest.emailmarketing.web.controllers.ImportController.java

/**
 * Import list./*  w  ww .j  a va  2s .c o  m*/
 *
 * @param model the model
 * @param request the request
 * @return the string
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws FileNotFoundException the file not found exception
 * @throws ParserConfigurationException the parser configuration exception
 * @throws TransformerException the transformer exception
 * @throws ServletException the servlet exception
 * @throws FileUploadException the file upload exception
 */
@RequestMapping(value = "/importList", method = RequestMethod.POST)
public String ImportList(Model model, HttpServletRequest request) throws IOException, FileNotFoundException,
        ParserConfigurationException, TransformerException, ServletException, FileUploadException {
    List<String> copypaste = new ArrayList<String>();
    String listfilename = "";
    String separator = "";
    String broadcast_id = "";
    String old_broadcast_id = "";
    String listType = "";
    EmailListForm emailListForm = new EmailListForm();

    InputStream fileContent = null;

    List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
    for (FileItem item : items) {
        if (item.isFormField()) {
            // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
            String fieldName = item.getFieldName();
            String fieldValue = item.getString();
            if (fieldName.equals("listType")) {
                listType = fieldValue;
                System.out.println(listType);
            } else if (fieldName.equals("copypaste")) {
                for (String line : fieldValue.split("\\n")) {
                    copypaste.add(line);
                    System.out.println(line);
                }
            } else if (fieldName.equals("listfilename")) {
                listfilename = fieldValue;
            } else if (fieldName.equals("separator")) {
                separator = fieldValue;
            } else if (fieldName.equals("broadcast_id")) {
                broadcast_id = fieldValue;
            } else if (fieldName.equals("old_broadcast_id")) {
                old_broadcast_id = fieldValue;
            }
        } else {
            // Process form file field (input type="file").
            String fieldName = item.getFieldName();
            String fileName = FilenameUtils.getName(item.getName());
            fileContent = item.getInputStream();
        }
        System.out.println(listfilename);
        System.out.println(separator);
    }
    int importCount = 0;
    if (listType.equals("copy")) {
        if (!copypaste.isEmpty()) {
            List<EmailList> eList = emailListService.importEmailfromCopy(copypaste, broadcast_id);
            emailListForm.setEmailList(eList);
            importCount = eList.size();
        } else {
            // sta ako je prazno
        }
    }
    if (listType.equals("fromfile")) {
        List<EmailList> eList = emailListService.importEmailfromFile(fileContent, separator, broadcast_id);
        emailListForm.setEmailList(eList);
        importCount = eList.size();
    }

    System.out.println(broadcast_id);
    model.addAttribute("importCount", importCount);
    model.addAttribute("emailListForm", emailListForm);
    Broadcast broadcast = broadcastService.getBroadcast(broadcast_id);
    System.out.println("Old broadcast: " + old_broadcast_id);
    if (!old_broadcast_id.isEmpty()) {
        model.addAttribute("old_broadcast_id", old_broadcast_id);
    }
    String message = null;
    if (broadcast.getBcast_template_id() != null) {
        message = "template";
    }
    model.addAttribute("message", message);
    model.addAttribute("broadcast_id", broadcast_id);
    return "importlistreport";
}

From source file:com.example.webapp.filter.MultipartFilter.java

/**
 * Process multipart request item as file field. The name and FileItem
 * object of each file field will be added as attribute of the given
 * HttpServletRequest. If a FileUploadException has occurred when the file
 * size has exceeded the maximum file size, then the FileUploadException
 * will be added as attribute value instead of the FileItem object.
 * //from   w  w w .j av  a2 s  . c  o  m
 * @param fileField The file field to be processed.
 * @param request The involved HttpServletRequest.
 */
private void processFileField(FileItem fileField, HttpServletRequest request) {
    if (fileField.getName().length() <= 0) {
        // No file uploaded.
        request.setAttribute(fileField.getFieldName(), null);
    } else if (maxFileSize > 0 && fileField.getSize() > maxFileSize) {
        // File size exceeds maximum file size.
        request.setAttribute(fileField.getFieldName(),
                new FileUploadException("File size exceeds maximum file size of " + maxFileSize + " bytes."));
        // Immediately delete temporary file to free up memory and/or disk
        // space.
        fileField.delete();
    } else {
        // File uploaded with good size.
        request.setAttribute(fileField.getFieldName(), fileField);
    }
}

From source file:net.daw.control.upload.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  ww  w . j  a  v  a 2s.c  om
 *
 * @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("application/json;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        String name = "";
        String strMessage = "";
        HashMap<String, String> hash = new HashMap<>();
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory())
                        .parseRequest(request);
                for (FileItem item : multiparts) {
                    if (!item.isFormField()) {
                        name = new File(item.getName()).getName();
                        item.write(new File(".//..//webapps//images//" + name));
                    } else {
                        hash.put(item.getFieldName(), item.getString());
                    }
                }
                Gson oGson = new Gson();
                Map<String, String> data = new HashMap<>();
                Iterator it = hash.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry e = (Map.Entry) it.next();
                    data.put(e.getKey().toString(), e.getValue().toString());
                }
                data.put("imglink", "http://" + request.getServerName() + ":" + request.getServerPort()
                        + "/images/" + name);
                out.print("{\"status\":200,\"message\":" + oGson.toJson(data) + "}");
            } catch (Exception ex) {
                strMessage += "File Upload Failed: " + ex;
                out.print("{\"status\":500,\"message\":\"" + strMessage + "\"}");
            }
        } else {
            strMessage += "Only serve file upload requests";
            out.print("{\"status\":500,\"message\":\"" + strMessage + "\"}");
        }
    }
}

From source file:com.ephesoft.dcma.gwt.admin.bm.server.UploadImageFileServlet.java

/**
 * Overridden doPost method.//  w w  w.  ja  v a2 s .c o m
 * 
 * @param request HttpServletRequest
 * @param response HttpServletResponse
 * @throws IOException
 */
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String batchClassId = null;
    String docName = null;
    String fileName = null;
    String isAdvancedTableInfo = null;
    InputStream instream = null;
    OutputStream out = null;
    PrintWriter printWriter = resp.getWriter();
    if (ServletFileUpload.isMultipartContent(req)) {
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items;
        BatchSchemaService batchSchemaService = this.getSingleBeanOfType(BatchSchemaService.class);
        String uploadPath = null;
        try {
            items = upload.parseRequest(req);
            for (FileItem item : items) {

                // process only file upload - discard other form item types
                if (item.isFormField()) {
                    if (item.getFieldName().equalsIgnoreCase("batchClassID")) {
                        batchClassId = item.getString();
                    } else if (item.getFieldName().equalsIgnoreCase("docName")) {
                        docName = item.getString();
                    } else if (item.getFieldName().equalsIgnoreCase("isAdvancedTableInfo")) {
                        isAdvancedTableInfo = item.getString();
                    }
                } else if (!item.isFormField() && "importFile".equals(item.getFieldName())) {
                    fileName = item.getName();
                    if (fileName != null) {
                        fileName = fileName.substring(fileName.lastIndexOf(File.separator) + 1);
                    }
                    instream = item.getInputStream();
                }
            }
            if (batchClassId == null || docName == null) {
                LOG.error(
                        "Error while loading image... Either batchClassId or doc type is null. Batch Class Id :: "
                                + batchClassId + " Doc Type :: " + docName);
                printWriter.write("Error while loading image... Either batchClassId or doc type is null.");
            } else {
                StringBuilder uploadPathString = uploadPath(batchClassId, docName, isAdvancedTableInfo,
                        batchSchemaService);
                File uploadFolder = new File(uploadPathString.toString());
                if (!uploadFolder.exists()) {
                    try {
                        boolean tempPath = uploadFolder.mkdirs();
                        if (!tempPath) {
                            LOG.error(
                                    "Unable to create the folders in the temp directory specified. Change the path and permissions in dcma-batch.properties");
                            printWriter.write(
                                    "Unable to create the folders in the temp directory specified. Change the path and permissions in dcma-batch.properties");
                            return;
                        }
                    } catch (Exception e) {
                        LOG.error("Unable to create the folders in the temp directory.", e);
                        printWriter
                                .write("Unable to create the folders in the temp directory." + e.getMessage());
                        return;
                    }
                }
                uploadPathString.append(File.separator);
                uploadPathString.append(fileName);
                uploadPath = uploadPathString.toString();
                out = new FileOutputStream(uploadPath);
                byte buf[] = new byte[BatchClassManagementConstants.BUFFER_SIZE];
                int len = instream.read(buf);
                while ((len) > 0) {
                    out.write(buf, 0, len);
                    len = instream.read(buf);
                }
                // convert tiff to png
                ImageProcessService imageProcessService = this.getSingleBeanOfType(ImageProcessService.class);
                imageProcessService.generatePNGForImage(new File(uploadPath));
                LOG.info("Png file created successfully for file: " + uploadPath);
            }
        } catch (FileUploadException e) {
            LOG.error("Unable to read the form contents." + e, e);
            printWriter.write("Unable to read the form contents.Please try again.");
        } catch (DCMAException e) {
            LOG.error("Unable to generate PNG." + e, e);
            printWriter.write("Unable to generate PNG.Please try again.");
        } finally {
            if (out != null) {
                out.close();
            }
            if (instream != null) {
                instream.close();
            }
        }
        printWriter.write("file_seperator:" + File.separator);
        printWriter.write("|");
    }
}

From source file:fina.usuario.servlet.usuarioServlet.java

private void modificarUsu(HttpServletRequest request, HttpServletResponse response,
        boolean modificarUsuarioSession) {

    JSONObject jsonResult = new JSONObject();
    Mensaje mensaje = new Mensaje(true, Mensaje.INFORMACION);
    boolean guardar = false;
    try {//ww w  .  j  av a2 s .  c om
        SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> listField = upload.parseRequest(request);
        Usuario usuario = new Usuario();
        UsuarioDao usuarioDao = new UsuarioDao();
        for (FileItem file : listField) {
            if (file.getFieldName().equals("txtNombres")) {
                usuario.setNombres(file.getString().trim());
            } else if (file.getFieldName().equals("txtApellidos")) {
                usuario.setApellidos(file.getString().trim());
            } else if (file.getFieldName().equals("txtFechaNacimiento")) {
                usuario.setFechaNacimiento(format.parse(file.getString().trim()));
            } else if (file.getFieldName().equals("txtUsuario")) {
                usuario.setUsername(file.getString().trim());
            } else if (file.getFieldName().equals("txtContrasenia")) {
                usuario.setContrasenia(file.getString());
            } else if (file.getFieldName().equals("rbSexo")) {
                usuario.setSexo("M".equals(file.getString()));
            } else if (file.getFieldName().equals("txtFoto")) {
                byte[] imagen = file.get();
                if (imagen != null && imagen.length > 0) {
                    usuario.setFoto(imagen);
                    usuario.setNombreFoto(file.getName());
                } else {
                    Usuario actual = usuarioDao.Obtener(usuario.getIdUSUARIO());
                    if (actual != null) {
                        usuario.setFoto(actual.getFoto());
                        usuario.setNombreFoto(actual.getNombreFoto());
                    }
                }
            } else if (file.getFieldName().equals("txtDNI")) {
                usuario.setDni(file.getString().trim());
            } else if (file.getFieldName().equals("tipoUsuario")) {
                Tipousuario tipou = usuarioDao.getTipousuarioById(file.getString().trim());
                usuario.setIdTipoUsuario(tipou);
            } else if (file.getFieldName().equals("txtIdUsuario")) {
                usuario.setIdUSUARIO(Integer.valueOf(file.getString().isEmpty() ? "-1" : file.getString()));
            } else if (file.getFieldName().equals("txtEstado")) {
                usuario.setEliminado(Boolean.valueOf(file.getString()));
            } else if (file.getFieldName().equals("txtGuardarUsuario")) {
                guardar = Boolean.valueOf(file.getString());
            }
        }
        if (usuario.getSexo() == null) {
            usuario.setSexo(true);
        }
        if (guardar) {
            usuario.setIdUSUARIO(null);
            usuarioDao.Insertar(usuario);
        } else {
            usuarioDao.Actualizar(usuario);
        }

        if (modificarUsuarioSession) {
            request.getSession().setAttribute("usuarioLogeado", usuario);
        }
        mensaje.setMensaje("Se registro correctamente.");

    } catch (Exception ex) {
        mensaje.establecerError(ex);
    }
    try {
        JSONObject jsonMensaje = new JSONObject(mensaje);
        jsonResult.put("msj", jsonMensaje);
        enviarDatos(response, jsonResult.toString());
    } catch (Exception ex) {
    }
}

From source file:admin.controller.ServletEditCategories.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* w w  w.j av  a  2s  .  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();

    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:FYPManagementSystem.FileUploadHandler.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String address = "";

    String option = request.getParameter("Option");
    String addTitle = "";
    String addContent = "";

    String query = "";
    String queryLastID = "";
    DB objDB = new DB();
    //process only if its multipart content
    if (option.equals("Add")) {

        if (ServletFileUpload.isMultipartContent(request)) {
            try {

                List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory())
                        .parseRequest(request);

                for (FileItem item : multiparts) {
                    if (!item.isFormField()) {
                        String name = new File(item.getName()).getName();
                        item.write(new File(UPLOAD_DIRECTORY + File.separator + addTitle + ".jpg"));
                    } else if (item.isFormField()) {
                        if (item.getFieldName().contentEquals("addTitle")) { //Check if the item in the loop is the user_id
                            addTitle = item.getString(); //If yes store the value
                        }/*  w  ww. j  a  v  a 2  s . c o m*/
                        if (item.getFieldName().contentEquals("addContent")) { //Check if the item in the loop is the user_id
                            addContent = item.getString(); //If yes store the value
                        }
                    }
                }
                query = "insert into news (newsTitle,newsContent) values('"
                        + Common.replaceSingleQuote(addTitle) + "','" + Common.replaceSingleQuote(addContent)
                        + "')";

                //File uploaded successfully
                request.setAttribute("message", "File Uploaded Successfully");
            } catch (Exception ex) {
                request.setAttribute("message", "File Upload Failed due to " + ex);
            }
            address = "WEB-INF/AdNews.jsp";
        } else {
            request.setAttribute("message", "Sorry this Servlet only handles file upload request");
        }
    }
    objDB.connect();
    objDB.query(query);
    objDB.close();

    RequestDispatcher dispatcher = request.getRequestDispatcher(address);
    dispatcher.forward(request, response);

}

From source file:admin.controller.ServletAddCategories.java

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