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.cloudbees.plugins.deployer.CloudbeesDeployWarTest.java

public void assertOnFileItems(String buildDescription) throws IOException {

    for (FileItem fileItem : cloudbeesServer.cloudbessServlet.items) {

        //archive check it's a war content

        //description check Jenkins BUILD_ID
        if (fileItem.getFieldName().equals("description")) {
            String description = fileItem.getString();
            assertEquals(buildDescription, description);
        } else if (fileItem.getFieldName().equals("api_key")) {
            assertEquals("Testing121212Testing", fileItem.getString());
        } else if (fileItem.getFieldName().equals("app_id")) {
            assertEquals("test-account/test-app", fileItem.getString());
        } else if (fileItem.getFieldName().equals("archive")) {
            assertOnArchive(fileItem.getInputStream());
        } else {/*from   w w w .ja  v a  2s .c  o m*/
            System.out.println(" item " + fileItem);
        }

    }

}

From source file:com.official.wears.site.UploadServlet.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  va  2 s .  com*/
    }
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize.
    factory.setRepository(new File("c:\\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>");
            }
        }
        out.println("</body>");
        out.println("</html>");
    } catch (Exception ex) {
        System.out.println(ex);
    }
}

From source file:com.github.davidcarboni.encryptedfileupload.StreamingTest.java

/**
 * Tests a file upload with varying file sizes.
 *///  ww w. j av  a2 s . c  o  m
public void testFileUpload() throws IOException, FileUploadException {
    byte[] request = newRequest();
    List<FileItem> fileItems = parseUpload(request);
    Iterator<FileItem> fileIter = fileItems.iterator();
    int add = 16;
    int num = 0;
    for (int i = 0; i < 16384; i += add) {
        if (++add == 32) {
            add = 16;
        }
        FileItem item = fileIter.next();
        assertEquals("field" + (num++), item.getFieldName());
        byte[] bytes = item.get();
        assertEquals(i, bytes.length);
        for (int j = 0; j < i; j++) {
            assertEquals((byte) j, bytes[j]);
        }
    }
    assertTrue(!fileIter.hasNext());
}

From source file:com.siberhus.web.ckeditor.servlet.BaseActionServlet.java

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String requestURI = request.getRequestURI();
    if (requestURI != null && requestURI.lastIndexOf("/") != -1) {
        String actionName = requestURI.substring(requestURI.lastIndexOf("/") + 1, requestURI.length());
        int paramIdx = actionName.indexOf("?");
        if (paramIdx != -1) {
            actionName = actionName.substring(0, actionName.indexOf("?"));
        }/*  ww w.  j  a v a  2 s .  c om*/
        Method method = null;
        try {
            method = this.getClass().getMethod(actionName, HttpServletRequest.class, HttpServletResponse.class);
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_NOT_FOUND,
                    "Action=" + actionName + " not found for servlet=" + this.getClass());
            return;
        }
        try {
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if (isMultipart) {
                request = new MultipartServletRequest(request);
                log.debug("Files *********************");
                MultipartServletRequest mrequest = (MultipartServletRequest) request;
                for (FileItem fileItem : mrequest.getFileItems()) {
                    log.debug("File[fieldName={}, fileName={}, fileSize={}]",
                            new Object[] { fileItem.getFieldName(), fileItem.getName(), fileItem.getSize() });
                }
            }
            if (log.isDebugEnabled()) {
                log.debug("Parameters **************************");
                Enumeration<String> paramNames = request.getParameterNames();
                while (paramNames.hasMoreElements()) {
                    String paramName = paramNames.nextElement();
                    log.debug("Param[name={},value(s)={}]",
                            new Object[] { paramName, Arrays.toString(request.getParameterValues(paramName)) });
                }
            }

            Object result = method.invoke(this, request, response);

            if (result instanceof StreamingResult) {
                if (!response.isCommitted()) {
                    ((StreamingResult) result).execute(request, response);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof InvocationTargetException) {
                throw new ServletException(((InvocationTargetException) e).getTargetException());
            }
            throw new ServletException(e);
        }
    }
}

From source file:game.com.HandleUploadGameThumbServlet.java

private void handle(HttpServletRequest request, AjaxResponseEntity responseObject) throws Exception {
    boolean isMultipart;
    String filePath;//w ww  . j  a  v a  2 s  .c  om
    int maxFileSize = 4 * 1024 * 1024;
    int maxMemSize = 4 * 1024 * 1024;
    File file;

    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("/tmp"));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);
    Map<String, List<FileItem>> postData = upload.parseParameterMap(request);
    String id = postData.get("id").get(0).getString();
    if (StringUtils.isBlank(id)) {
        logger.info("id= " + id);
    }

    try {
        // Parse the request to get file items.
        List<FileItem> fileItems = postData.get("image");
        // Process the uploaded file items

        for (FileItem fi : fileItems) {
            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
                file = new File(AppConfig.OPENSHIFT_DATA_DIR + "/thumb/" + id + ".png");
                //                    Image img = ImageIO.read(fi.getInputStream());
                //                    BufferedImage tempPNG = resizeImage(img, 256, 240);
                //                    ImageIO.write(tempPNG, "png", file);
                fi.write(file);
                responseObject.data = getThumbUrl(id);
                responseObject.returnCode = 1;
                responseObject.returnMessage = "success";
                break;
            } else {
                logger.info("isFormField " + fi.getFieldName());
            }
        }

    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
    }
}

From source file:imageServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*  w  w  w .  j  a  va2  s.  co m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String name = "";
    String value = "";
    String imageurl = "";
    String path = "";
    try {
        String ImageFile = "";
        String itemName = "";

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (!isMultipart) {
        } else {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = null;
            try {
                items = upload.parseRequest(request);
            } catch (FileUploadException e) {
                System.out.println("Exception in upload");
                e.getMessage();
            }

            Iterator itr = items.iterator();
            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();
                if (item.isFormField()) {
                    name = item.getFieldName();
                    value = item.getString();
                    if (name.equals("ImageFile")) {
                        ImageFile = value;
                    }

                } else {
                    try {

                        itemName = item.getName();
                        File savedFile = new File(
                                this.getServletContext().getRealPath("/") + "images\\" + itemName);
                        File image = new File(request.getParameter("ImageFile"));
                        path = "/images/";
                        name = itemName;
                        item.write(savedFile);
                    } catch (Exception e) {
                        System.out.println("Error" + e.getMessage());
                    }
                }
            }
            try {
                int image = StudyDB.uploadImage("/images/" + itemName);
                imageurl = StudyDB.retrieveImage();

            } catch (Exception el) {
                System.out.println("Inserting error" + el.getMessage());
            }
        }
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
    String URL = "/displayImage.jsp";
    String message = "Success";
    request.setAttribute("message", message);
    request.setAttribute("imageurl", imageurl);
    getServletContext().getRequestDispatcher(URL).forward(request, response);

}

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   w  w  w .j av  a  2s . c om
        // 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:net.formio.upload.MultipartRequestPreprocessor.java

private void addMultivaluedItem(FileItem item) {
    List<String> values = regularParams.get(item.getFieldName());
    addItemValue(values, item);
}

From source file:adminServlets.AddProductServlet.java

private void uploadImage(HttpServletRequest request, HttpServletResponse response) {
    PrintWriter out = null;/*from   ww  w . j  a  v a 2  s  . c  o  m*/
    try {

        out = response.getWriter();
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> iter = items.iterator();

        while (iter.hasNext()) {

            FileItem item = (FileItem) iter.next();

            if (item.isFormField()) {
                String name = item.getFieldName();
                String value = item.getString();
                paramaters.put(name, value);

            } else // processUploadedFile(item);
            {
                if (item.getSize() != 0) {
                    String itemName = item.getName();
                    Random generator = new Random();
                    int r = Math.abs(generator.nextInt());

                    String reg = "[.*]";
                    String replacingtext = "";

                    Pattern pattern = Pattern.compile(reg);
                    Matcher matcher = pattern.matcher(itemName);
                    StringBuffer buffer = new StringBuffer();

                    while (matcher.find()) {
                        matcher.appendReplacement(buffer, replacingtext);
                    }
                    int IndexOf = itemName.indexOf(".");
                    String domainName = itemName.substring(IndexOf);

                    String finalimage = buffer.toString() + "_" + r + domainName;

                    String path = "assets\\img\\bouques\\" + finalimage;
                    imgPaths.add(path);
                    File savedFile = new File(getServletContext().getRealPath("/") + path);

                    try {
                        item.write(savedFile);
                    } catch (Exception ex) {
                        Logger.getLogger(AddProductServlet.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        }
    } catch (IOException | FileUploadException ex) {
        Logger.getLogger(AddProductServlet.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
    }

}

From source file:eu.stratosphere.client.web.JobsServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // check, if we are doing the right request
    if (!ServletFileUpload.isMultipartContent(req)) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;/*www . j  a va2  s  .  com*/
    }

    // create the disk file factory, limiting the file size to 20 MB
    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
    fileItemFactory.setSizeThreshold(20 * 1024 * 1024); // 20 MB
    fileItemFactory.setRepository(tmpDir);

    String filename = null;

    // parse the request
    ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
    try {
        @SuppressWarnings("unchecked")
        Iterator<FileItem> itr = ((List<FileItem>) uploadHandler.parseRequest(req)).iterator();

        // go over the form fields and look for our file
        while (itr.hasNext()) {
            FileItem item = itr.next();
            if (!item.isFormField()) {
                if (item.getFieldName().equals("upload_jar_file")) {

                    // found the file, store it to the specified location
                    filename = item.getName();
                    File file = new File(destinationDir, filename);
                    item.write(file);
                    break;
                }
            }
        }
    } catch (FileUploadException ex) {
        resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Invalid Fileupload.");
        return;
    } catch (Exception ex) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "An unknown error occurred during the file upload.");
        return;
    }

    // write the okay message
    resp.sendRedirect(targetPage);
}