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:com.servlet.tools.FileUploadHelper.java

private List<Integer> GetFileItemNumber(List<FileItem> fileItemList) {
    List<Integer> numberList;
    int i = 0;//ww w.  ja v a  2s.c om
    numberList = new ArrayList();
    for (FileItem itemTemp : fileItemList) {
        if (!itemTemp.isFormField()) {
            numberList.add(i);
        }
        i++;
    }
    return numberList;
}

From source file:controller.addGame.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {

        boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
        if (isMultiPart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = upload.parseRequest(request);
            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem fileItem = iter.next();
                if (fileItem.isFormField()) {
                    processFormField(fileItem);
                } else {
                    flItem = fileItem;/*from w ww  . jav  a 2  s . c  om*/
                }
            }
        }

        Connect obj_con = new Connect();
        Connection con = obj_con.Open();

        String sql = "insert into Application_Names values(?,?,?)";
        String sql1 = "insert into required_Minimum values(?,?,?,?,?,?)";
        String sql2 = "insert into required_Recomended values(?,?,?,?,?,?)";

        PreparedStatement pr = con.prepareStatement(sql);
        PreparedStatement pr1 = con.prepareStatement(sql1);
        PreparedStatement pr2 = con.prepareStatement(sql2);

        pr.setString(1, AppName);
        pr.setString(2, Code);
        pr.setString(3, Code);

        pr1.setString(1, Code);
        pr1.setString(2, MinGpu);
        pr1.setInt(3, MinGpuLvl);
        pr1.setString(4, MinCpu);
        pr1.setInt(5, RecCpuLvl);
        pr1.setInt(6, MinRam);

        pr2.setString(1, Code);
        pr2.setString(2, RecGpu);
        pr2.setInt(3, RecGpuLvl);
        pr2.setString(4, RecCpu);
        pr2.setInt(5, RecCpuLvl);
        pr2.setInt(6, RecRam);

        int a = pr.executeUpdate();
        int b = pr1.executeUpdate();
        int c = pr2.executeUpdate();

        if (a > 0 && b > 0 && c > 0) {
            RequestDispatcher rd = request.getRequestDispatcher("viewGames.jsp");
            request.setAttribute("return", "Added Item Succesfully.");
            rd.forward(request, response);

            pr.close();
            pr1.close();
            pr2.close();
            con.close();
        } else {
            RequestDispatcher rd = request.getRequestDispatcher("addGame.jsp");
            request.setAttribute("return", "Added Item Succesfully.");
            rd.forward(request, response);
        }

    } catch (Exception e) {
        System.out.println(e.getCause());
    }
}

From source file:UploadImage.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //  change the following parameters to connect to the oracle database
    String username = "lingbo";
    String password = "TlboSci1994";
    String drivername = "oracle.jdbc.driver.OracleDriver";
    String dbstring = "jdbc:oracle:thin:@gwynne.cs.ualberta.ca:1521:CRS";
    int pic_id;/*  www .jav a  2 s. c  om*/

    try {
        //Parse the HTTP request to get the image stream
        DiskFileUpload fu = new DiskFileUpload();
        List FileItems = fu.parseRequest(request);

        // Process the uploaded items, assuming only 1 image file uploaded
        Iterator i = FileItems.iterator();
        FileItem item = (FileItem) i.next();
        while (i.hasNext() && item.isFormField()) {
            item = (FileItem) i.next();
        }

        //Get the image stream
        InputStream instream = item.getInputStream();

        BufferedImage img = ImageIO.read(instream);
        BufferedImage thumbNail = shrink(img, 10);

        // Connect to the database and create a statement
        Connection conn = getConnected(drivername, dbstring, username, password);
        Statement stmt = conn.createStatement();

        /*
         *  First, to generate a unique pic_id using an SQL sequence
         */
        ResultSet rset1 = stmt.executeQuery("SELECT pic_id_sequence.nextval from dual");
        rset1.next();
        pic_id = rset1.getInt(1);

        //Insert an empty blob into the table first. Note that you have to 
        //use the Oracle specific function empty_blob() to create an empty blob
        stmt.execute("INSERT INTO pictures VALUES(" + pic_id + ",'test',empty_blob())");

        // to retrieve the lob_locator 
        // Note that you must use "FOR UPDATE" in the select statement
        String cmd = "SELECT * FROM pictures WHERE pic_id = " + pic_id + " FOR UPDATE";
        ResultSet rset = stmt.executeQuery(cmd);
        rset.next();
        BLOB myblob = ((OracleResultSet) rset).getBLOB(3);

        //Write the image to the blob object
        OutputStream outstream = myblob.setBinaryStream(1);
        ImageIO.write(thumbNail, "jpg", outstream);

        /*
        int size = myblob.getBufferSize();
        byte[] buffer = new byte[size];
        int length = -1;
        while ((length = instream.read(buffer)) != -1)
        outstream.write(buffer, 0, length);
        */
        instream.close();
        outstream.close();

        stmt.executeUpdate("commit");
        response_message = " Upload OK!  ";
        conn.close();

    } catch (Exception ex) {
        //System.out.println( ex.getMessage());
        response_message = ex.getMessage();
    }

    //Output response to the client
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n" + "<HTML>\n"
            + "<HEAD><TITLE>Upload Message</TITLE></HEAD>\n" + "<BODY>\n" + "<H1>" + response_message
            + "</H1>\n" + "</BODY></HTML>");
}

From source file:com.nemesis.admin.UploadServlet.java

/**
 * @param request/*from   w  ww  .ja  v  a 2 s.c  om*/
 * @param response
 * @throws javax.servlet.ServletException
 * @throws java.io.IOException
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 * response)
 *
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new IllegalArgumentException(
                "Request is not multipart, please 'multipart/form-data' enctype for your form.");
    }

    ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory());
    PrintWriter writer = response.getWriter();
    response.setContentType("application/json");
    JsonArray json = new JsonArray();
    try {
        List<FileItem> items = uploadHandler.parseRequest(request);
        for (FileItem item : items) {
            if (!item.isFormField()) {
                final String savedFile = UUID.randomUUID().toString() + "." + getSuffix(item.getName());
                File file = new File(request.getServletContext().getRealPath("/") + "uploads/", savedFile);
                item.write(file);
                JsonObject jsono = new JsonObject();
                jsono.addProperty("name", savedFile);
                jsono.addProperty("path", file.getAbsolutePath());
                jsono.addProperty("size", item.getSize());
                json.add(jsono);
                System.out.println(json.toString());
            }
        }
    } catch (FileUploadException e) {
        throw new RuntimeException(e);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        writer.write(json.toString());
        writer.close();
    }

}

From source file:Control.LoadImage.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from  www .ja v a 2 s.c om
 * @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 {
    String tempPath = "/temp";
    String absoluteTempPath = this.getServletContext().getRealPath(tempPath);
    String absoluteFilePath = this.getServletContext().getRealPath("/data/Image");
    int maxFileSize = 50 * 1024;
    int maxMemSize = 4 * 1024;

    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(maxMemSize);
        File file = new File(absoluteTempPath);

        if (file == null) {
            // tao thu muc
        }

        factory.setRepository(file);
        ServletFileUpload upload = new ServletFileUpload(factory);

        //upload.setProgressListener(new MyProgressListener(out));
        List<FileItem> items = upload.parseRequest(request);

        if (items.size() > 0) {
            for (FileItem item : items) {
                if (!item.isFormField()) {
                    if ("images".equals(item.getFieldName())) {
                        if (item.getName() != null && !item.getName().isEmpty()) {
                            String extension = null;
                            if (item.getName().endsWith("jpg")) {
                                String newLink = "/Image/" + Image.LengthListImg() + ".jpg";
                                file = new File(absoluteFilePath + "//" + Image.LengthListImg() + ".jpg");
                                // G?i hm add hnh vo database, link hnh l newLink
                                item.write(file);
                            } else if (item.getName().endsWith("png")) {
                                String newLink = "/Image/" + Image.LengthListImg() + ".png";
                                file = new File(absoluteFilePath + "//" + Image.LengthListImg() + ".png");
                                // G?i hm add hnh vo database, link hnh l newLink
                                item.write(file);
                            } else if (item.getName().endsWith("JPG")) {
                                String newLink = "/Image/" + Image.LengthListImg() + ".JPG";
                                file = new File(absoluteFilePath + "//" + Image.LengthListImg() + ".JPG");
                                // G?i hm add hnh vo database, link hnh l newLink
                                item.write(file);
                            } else if (item.getName().endsWith("PNG")) {
                                String newLink = "/Image/" + Image.LengthListImg() + ".PNG";
                                file = new File(absoluteFilePath + "//" + Image.LengthListImg() + ".PNG");
                                // G?i hm add hnh vo database, link hnh l newLink
                                item.write(file);
                            }
                        }
                    }
                } else {
                }
            }
            response.sendRedirect(request.getContextPath() + "/LoadImage.jsp");
            return;
        }

        List<Image> images = loadImages(request, response);

        request.setAttribute("images", images);
        request.setAttribute("error", "No file upload");
        RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/LoadImage.jsp");
        dispatcher.forward(request, response);
    } catch (Exception ex) {
        System.err.println(ex);
    }
}

From source file:com.ephesoft.gxt.foldermanager.server.UploadDownloadFilesServlet.java

private void uploadFile(HttpServletRequest req, HttpServletResponse resp, String currentBatchUploadFolderName)
        throws IOException {

    PrintWriter printWriter = resp.getWriter();
    File tempFile = null;/*from   w w  w. j  a va  2 s .com*/
    InputStream instream = null;
    OutputStream out = null;
    String uploadFileName = "";
    try {
        if (ServletFileUpload.isMultipartContent(req)) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            uploadFileName = "";
            String uploadFilePath = "";
            List<FileItem> items;
            try {
                items = upload.parseRequest(req);
                for (FileItem item : items) {
                    if (!item.isFormField()) {
                        uploadFileName = item.getName();
                        if (uploadFileName != null) {
                            uploadFileName = uploadFileName
                                    .substring(uploadFileName.lastIndexOf(File.separator) + 1);
                        }
                        uploadFilePath = currentBatchUploadFolderName + File.separator + uploadFileName;
                        try {
                            instream = item.getInputStream();
                            tempFile = new File(uploadFilePath);

                            out = new FileOutputStream(tempFile);
                            byte buf[] = new byte[1024];
                            int len;
                            while ((len = instream.read(buf)) > 0) {
                                out.write(buf, 0, len);
                            }
                        } catch (FileNotFoundException e) {
                            printWriter.write("Unable to create the upload folder.Please try again.");

                        } catch (IOException e) {
                            printWriter.write("Unable to read the file.Please try again.");
                        } finally {
                            if (out != null) {
                                out.close();
                            }
                            if (instream != null) {
                                instream.close();
                            }
                        }
                    }
                }
            } catch (FileUploadException e) {
                printWriter.write("Unable to read the form contents.Please try again.");
            }

        } else {
            printWriter.write("Request contents type is not supported.");
        }
        printWriter.write("currentBatchUploadFolderName:" + currentBatchUploadFolderName);
        printWriter.append("|");

        printWriter.append("fileName:").append(uploadFileName);
        printWriter.append("|");
    } finally {
        printWriter.flush();
        printWriter.close();
    }
}

From source file:controller.UpdateEC.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");
    ExtenuatingCircumstance ec = new ExtenuatingCircumstance();
    if (ServletFileUpload.isMultipartContent(request)) {
        try {
            String fname = StringUtils.EMPTY;
            String title = StringUtils.EMPTY;
            String desciption = StringUtils.EMPTY;
            String status = StringUtils.EMPTY;
            int id = 0;
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
            ArrayList<FileItem> files = new ArrayList<>();
            for (FileItem item : multiparts) {
                if (item.isFormField()) {
                    if (item.getFieldName().equals("id")) {
                        id = Integer.parseInt(item.getString());
                        System.out.println("id: " + id);
                    }
                    if (item.getFieldName().equals("title")) {
                        title = item.getString();
                    }
                    if (item.getFieldName().equals("description")) {
                        desciption = item.getString();
                    }
                    if (item.getFieldName().equals("status")) {
                        status = item.getString();
                        System.out.println("status: " + status);
                    }

                } else {
                    if (StringUtils.isNotEmpty(item.getName())) {
                        files.add(item);
                    }
                }
            }

            HttpSession session = request.getSession(false);
            Account studentAccount = (Account) session.getAttribute("account");
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");
            LocalDateTime now = LocalDateTime.now();

            // insert EC
            ec.setId(id);
            ec.setTitle(title);
            ec.setDescription(desciption);
            ec.setProcess_status(status);
            //ec.setSubmitted_date(now.toString());
            ec.setAccount(studentAccount.getId());

            new ExtenuatingCircumstanceDAO().updateEC(ec, "student");

            //insert additional evident evidence
            if (files.size() > 0) {
                insertedEvidence(files, now, ec, studentAccount);
            }

            request.setAttribute("resultMsg", "updated");
            request.getRequestDispatcher("AddNewECResult.jsp").forward(request, response);

        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        request.setAttribute("message", "Sorry this Servlet only handles file upload request");
    }
}

From source file:com.arcadian.loginservlet.LecturesServlet.java

/**
 * Handles the HTTP//  ww  w.  j a v  a  2 s. c o m
 * <code>POST</code> method.
 *
 * @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
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new ServletException("Content type is not multipart/form-data");
    }
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    try {
        List<FileItem> fileItemsList = uploader.parseRequest(request);
        Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
        String lectureid = "";
        String lecturename = "";
        String subjectid = "";
        String classname = "";
        while (fileItemsIterator.hasNext()) {
            FileItem fileItem = fileItemsIterator.next();
            if (fileItem.isFormField()) {

                String name = fileItem.getFieldName();
                System.out.println(name);

                String value = fileItem.getString();
                System.out.println(value);

                if (name.equalsIgnoreCase("lectureid")) {
                    lectureid = value;
                }
                if (name.equalsIgnoreCase("lecturename")) {
                    lecturename = value;
                }
                if (name.equalsIgnoreCase("subjectid")) {
                    subjectid = value;
                }
                if (name.equalsIgnoreCase("semname")) {
                    classname = value;
                }

            }

            if (fileItem.getName() != null) {

                File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator
                        + fileItem.getName());
                System.out.println("Absolute Path at server=" + file.getAbsolutePath());
                fileItem.write(file);

                lecturesService = new LecturesService();
                lecturesService.updateLectures(lectureid, lecturename, classname, subjectid, username,
                        fileItem.getName());
            }
        }

    } catch (FileUploadException e) {
        System.out.println("Exception in file upload" + e);
    } catch (Exception ex) {
        Logger.getLogger(CourseContentServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
    processRequest(request, response);
}

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

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    response.setContentType("text/html");
    log("Content-Type: " + request.getContentType());

    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
    /*//from  w w  w. j a v  a2s  . c om
     *Set the size threshold, above which content will be stored on disk.
     */
    fileItemFactory.setSizeThreshold(10 * 1024 * 1024); //10 MB
    /*
    * Set the temporary directory to store the uploaded files of size above threshold.
    */
    fileItemFactory.setRepository(tmpDir);

    ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
    try {
        /*
         * Parse the request
         */
        List items = uploadHandler.parseRequest(request);
        log("FileItems: " + items.toString());
        Iterator itr = items.iterator();
        while (itr.hasNext()) {

            FileItem item = (FileItem) itr.next();
            /*
             * Handle Form Fields.
             */
            if (item.isFormField()) {
                out.println("File Name = " + item.getFieldName() + ", Value = " + item.getString());
            } else {
                //Handle Uploaded files.
                out.println("<html><head><title>CommonsFileUploadServlet</title></head><body><p>");
                out.println("Field Name = " + item.getFieldName() + "\nFile Name = " + item.getName()
                        + "\nContent type = " + item.getContentType() + "\nFile Size = " + item.getSize());
                out.println("</p>");
                out.println("<img src=\"" + request.getContextPath() + "/files/" + item.getName() + "\"/>");
                out.println("</body></html>");
                /*
                 * Write file to the ultimate location.
                 */
                File file = new File(destinationDir, item.getName());
                item.write(file);
            }
            out.close();
        }
    } catch (FileUploadException ex) {
        log("Error encountered while parsing the request", ex);
    } catch (Exception ex) {
        log("Error encountered while uploading file", ex);
    }
}

From source file:de.betterform.agent.web.servlet.UploadServlet.java

private void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String payload = "";
    try {//from w w  w. jav a 2 s . c  o m
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List /* FileItem */ items = upload.parseRequest(request);

        Iterator iter = items.iterator();
        FileItem uploadItem = null;
        String collectionPath = "";
        String collectionName = "";
        String relativeUploadPath = "";
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            String fieldName = item.getFieldName();
            if (item.isFormField() && "bfUploadPath".equals(fieldName)) {
                relativeUploadPath = this.getFieldValue(item);
            } else if (item.isFormField() && "bfCollectionPath".equals(fieldName)) {
                collectionPath = this.getFieldValue(item);
            } else if (item.isFormField() && "bfCollectionName".equals(fieldName)) {
                collectionName = this.getFieldValue(item);
            } else if (item.getName() != null) {
                // FileItem of the uploaded file
                uploadItem = item;
            }
        }

        if (uploadItem != null && !"".equals(relativeUploadPath)) {
            this.uploadFile(request, uploadItem, relativeUploadPath);
        } else if (!"".equals(collectionName) && !"".equals(collectionPath)) {
            this.createColection(request, collectionName, collectionPath);
        } else {
            LOGGER.warn("error uploading file to '" + relativeUploadPath + "'");
        }
    } catch (FileUploadException e) {
        e.printStackTrace();
        payload = e.getMessage();
    } catch (Exception e) {
        e.printStackTrace();
        payload = e.getMessage();
    }
    response.getOutputStream().println("<html><body><textarea>" + payload + "</textarea></body></html>");
}