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:ned.bcvs.admin.fileupload.ConstituencyFileUploadServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {
    // Check that we have a file upload request
    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    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;/*w ww  . java 2 s  .  c  o  m*/
    }
    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(
            "D:/glassfish12October/glassfish-4.0/glassfish4/" + "glassfish/domains/domain1/applications/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();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        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();
                // 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>");
            }
        }
        //calling the ejb method to save constituency.csv file to data base
        out.println(upbean.fileDbUploader(filePath + fileName, "constituency"));
        out.println("</body>");
        out.println("</html>");
    } catch (Exception ex) {
        System.out.println(ex);
    }
}

From source file:com.auction.servlet.FileUploadServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   ww  w .java  2  s  .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
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setContentType("text/html;charset=UTF-8");
    response.addHeader("Access-Control-Allow-Origin", "*");
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);

        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            try {
                String randomFileName = StringUtils.getRandomString() + ".jpg";
                List items = upload.parseRequest(request);
                Iterator iterator = items.iterator();
                while (iterator.hasNext()) {
                    FileItem item = (FileItem) iterator.next();

                    if (!item.isFormField()) {
                        //String fileName = item.getName();

                        String root = getServletContext().getRealPath("/");
                        File path = new File(root + "/uploads");
                        if (!path.exists()) {
                            boolean status = path.mkdirs();
                        }

                        //File uploadedFile = new File(path + "/" + fileName);
                        File uploadedFile = new File(path + "/" + randomFileName);
                        System.out.println(uploadedFile.getAbsolutePath());
                        item.write(uploadedFile);
                    }
                }
                out.print(randomFileName);
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.silverpeas.gallery.servlets.GalleryDragAndDrop.java

private String getParameterValue(List<FileItem> items, String parameterName) {
    for (FileItem item : items) {
        if (item.isFormField() && parameterName.equals(item.getFieldName())) {
            return item.getString();
        }// w w  w  .  j  a  va  2s  .  c o  m
    }
    return null;
}

From source file:juzu.plugin.upload.FileUploadUnmarshaller.java

@Override
public void unmarshall(String mediaType, final ClientContext context,
        Iterable<Map.Entry<ContextualParameter, Object>> contextualArguments,
        Map<String, RequestParameter> parameterArguments) throws IOException {

    org.apache.commons.fileupload.RequestContext ctx = new org.apache.commons.fileupload.RequestContext() {
        public String getCharacterEncoding() {
            return context.getCharacterEncoding();
        }/* w  w w .j  a  va2  s  .  c  o m*/

        public String getContentType() {
            return context.getContentType();
        }

        public int getContentLength() {
            return context.getContentLenth();
        }

        public InputStream getInputStream() throws IOException {
            return context.getInputStream();
        }
    };

    //
    FileUpload upload = new FileUpload(new DiskFileItemFactory());
    try {
        List<FileItem> list = (List<FileItem>) upload.parseRequest(ctx);
        HashMap<String, FileItem> files = new HashMap<String, FileItem>();
        for (FileItem file : list) {
            String name = file.getFieldName();
            if (file.isFormField()) {
                RequestParameter parameterArg = parameterArguments.get(name);
                if (parameterArg == null) {
                    parameterArguments.put(name, RequestParameter.create(name, file.getString()));
                } else {
                    parameterArguments.put(name, parameterArg.append(new String[] { file.getString() }));
                }
            } else {
                files.put(name, file);
            }
        }
        for (Map.Entry<ContextualParameter, Object> argument : contextualArguments) {
            ContextualParameter contextualParam = argument.getKey();
            FileItem file = files.get(contextualParam.getName());
            if (file != null && FileItem.class.isAssignableFrom(contextualParam.getType())) {
                argument.setValue(file);
            }
        }
    } catch (FileUploadException e) {
        throw new IOException(e);
    }
}

From source file:ned.bcvs.admin.fileupload.CandidateFileUploadServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {
    // Check that we have a file upload request
    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    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;/*from www. java  2  s .  c  om*/
    }
    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(
            "D:/glassfish12October/glassfish-4.0/glassfish4/" + "glassfish/domains/domain1/applications/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();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        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();
                // 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>");

            }
        }
        //calling the ejb method to save voter.csv file to data base
        out.println(upbean.fileDbUploader(filePath + fileName, "candidate"));
        out.println("</body>");
        out.println("</html>");
    } catch (Exception ex) {
        System.out.println(ex);
    }
}

From source file:controllers.ControladorFotoCoin.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//w  ww. j  av  a2  s.  c  o 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 {
    int idMatch = Integer.parseInt(request.getParameter("idMatch"));
    String userPath = "";
    String UPLOAD_DIRECTORY = "/Users/patriciacuevas/NetBeansProjects/PerfectMatchTis2/web/fotosUsuarios";
    if (ServletFileUpload.isMultipartContent(request)) {
        String pathFile = "";
        try {
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    String name = new File(item.getName()).getName();
                    pathFile = UPLOAD_DIRECTORY + File.separator + name;
                    item.write(new File(pathFile));

                }
            }

            PmtMatchDTO match = new PmtMatchDTO();
            match.setMatId(idMatch);

            PmtIntercambioFotosDTO intercambio = new PmtIntercambioFotosDTO();
            intercambio.setInfRutaUsuarioCoincidente(pathFile);
            intercambio.setMat(match);

            intercambio.guardar(intercambio);

            request.setAttribute("message", "Su foto fue enviada exitosamente");
            userPath = "cliente";

        } catch (Exception ex) {
            request.setAttribute("message", "Error al cargar el archivo");
            userPath = "enviarFotoCoincidente";
        }

        String url = "WEB-INF/view/" + userPath + ".jspf";
        RequestDispatcher rd = request.getRequestDispatcher(url);
        rd.forward(request, response);
    }
}

From source file:ned.bcvs.admin.fileupload.ElectionPartyFileUploadServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {
    // Check that we have a file upload request
    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    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;//w  ww  .j  a v a 2 s .  co  m
    }
    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(
            "D:/glassfish12October/glassfish-4.0/glassfish4/" + "glassfish/domains/domain1/applications/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();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                String fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();
                // 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>");
            }
        }

        //calling the ejb method to save voter.csv file to data base
        out.println(upbean.fileDbUploader(filePath + fileName, "electionparty"));
        out.println("</body>");
        out.println("</html>");
    } catch (Exception ex) {
        System.out.println(ex);
    }
}

From source file:ned.bcvs.fileupload.ElectionPartyFileUploadServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {
    // Check that we have a file upload request
    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    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;/*from w  w  w .  ja v a2s. c o  m*/
    }
    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(
            "D:/glassfish12October/glassfish-4.0/glassfish4/" + "glassfish/domains/domain1/applications/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();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        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();
                // 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>");
            }
        }

        //calling the ejb method to save voter.csv file to data base
        out.println(upbean.fileDbUploader(filePath + fileName, "electionparty"));
        out.println("</body>");
        out.println("</html>");
    } catch (Exception ex) {
        System.out.println(ex);
    }
}

From source file:CommonServlets.EditUser.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String email = null, userName = null, job = null, address = null, password = null, img = null, role = null;
    BigDecimal creditLimit = new BigDecimal(0);

    try {/*from www . j  a  v  a 2s  . co  m*/
        // 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(request);
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();
            if (item.isFormField()) {
                //processFormField(item);
                String name = item.getFieldName();
                String value = item.getString();

                if (name.equalsIgnoreCase("email")) {
                    email = value;
                } else if (name.equalsIgnoreCase("userName")) {
                    userName = value;
                } else if (name.equalsIgnoreCase("creditLimit")) {
                    DecimalFormatSymbols symbols = new DecimalFormatSymbols();
                    symbols.setGroupingSeparator(',');
                    symbols.setDecimalSeparator('.');
                    String pattern = "#,##0.0#";
                    DecimalFormat decimalFormat = new DecimalFormat(pattern, symbols);
                    decimalFormat.setParseBigDecimal(true);
                    creditLimit = (BigDecimal) decimalFormat.parse(value);
                } else if (name.equalsIgnoreCase("job")) {
                    job = value;

                } else if (name.equalsIgnoreCase("address")) {
                    address = value;
                } else if (name.equalsIgnoreCase("password")) {
                    password = value;
                }
            } else if (!item.isFormField() && !item.getName().equals("")) {
                System.out.println(new File(AddProduct.class.getClassLoader().getResource("").getPath()
                        .replace("%20", " ")
                        .substring(0, AddProduct.class.getClassLoader().getResource("").getPath()
                                .replace("%20", " ").length() - 27)
                        + "/web/Resources/users_pics/" + item.getName()));
                item.write(new File(AddProduct.class.getClassLoader().getResource("").getPath()
                        .replace("%20", " ")
                        .substring(0, AddProduct.class.getClassLoader().getResource("").getPath()
                                .replace("%20", " ").length() - 27)
                        + "/web/Resources/users_pics/" + item.getName()));
                img = item.getName();
            }
        }

        User u = new User(email, userName, password, creditLimit, job, address, img, role);
        controlServlet.editUserDate(u);
        HttpSession session = request.getSession(true);
        session.setAttribute("done", "1");
        ControlServlet c = new ControlServlet();
        User myUser = c.getUser(userName);
        session.setAttribute("user", myUser);
        response.sendRedirect("UserHome.jsp");

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

From source file:dk.cphbusiness.codecheck.web.Upload.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request/*from www.j  a v  a  2 s . co 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 {
    Enumeration<String> paramNames = request.getParameterNames();
    while (paramNames.hasMoreElements()) {
        String name = paramNames.nextElement();
        String value = request.getParameter(name);
        System.out.println(name + ": " + value);
    }
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {
        try (PrintWriter out = response.getWriter()) {
            out.println("Error: not a multipart request.");
            return;
        }
    }

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

    // Configure a repository (to ensure a secure temp location is used)
    //ServletContext servletContext = this.getServletConfig().getServletContext();
    //File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
    File repository = new File(Config.UPLOAD_FOLDER);
    factory.setRepository(repository);

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    int taskID = -1;
    try {
        // Parse the request
        List<FileItem> items = upload.parseRequest(request);
        FileItem ft = null;
        for (FileItem item : items) {
            if (item.isFormField()) {
                if ("TaskID".equals(item.getFieldName())) {
                    taskID = Integer.parseInt(item.getString());
                }
            } else {
                ft = item;
            }
        }
        if (taskID > 0 && ft != null) {
            int reportID = DBUtil.createReport(taskID);
            String fileName = "HandIn_" + reportID + ".jar";
            ft.write(new File(Config.UPLOAD_FOLDER + fileName));
            Task task = DBUtil.getTask(taskID);
            CodeChecker codeChecker = new CodeChecker(reportID, task, fileName);
            Thread t = new Thread(codeChecker);
            t.start();
            //codeChecker.run();
            response.sendRedirect("/CodeCheckWeb/ShowReport?ReportID=" + reportID);
        }
    } catch (FileUploadException ex) {
        Logger.getLogger(Upload.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(Upload.class.getName()).log(Level.SEVERE, null, ex);
    }

}