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

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

Introduction

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

Prototype

String getString();

Source Link

Document

Returns the contents of the file item as a String, using the default character encoding.

Usage

From source file:adminShop.registraProducto.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//w ww .  java  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
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String message = "Error";
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items;
        HashMap hm = new HashMap();
        ArrayList<Imagen> imgs = new ArrayList<>();
        Producto prod = new Producto();
        Imagen img = null;
        try {
            items = upload.parseRequest(request);
            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = iter.next();
                if (item.isFormField()) {
                    String name = item.getFieldName();
                    String value = item.getString();
                    hm.put(name, value);
                } else {
                    img = new Imagen();
                    String fieldName = item.getFieldName();
                    String fileName = item.getName();
                    String contentType = item.getContentType();
                    boolean isInMemory = item.isInMemory();
                    long sizeBytes = item.getSize();
                    File file = new File("/home/gama/Escritorio/adoo/" + fileName + ".jpg");
                    item.write(file);
                    Path path = Paths.get("/home/gama/Escritorio/adoo/" + fileName + ".jpg");
                    byte[] data = Files.readAllBytes(path);
                    byte[] encode = org.apache.commons.codec.binary.Base64.encodeBase64(data);
                    img.setUrl(new javax.sql.rowset.serial.SerialBlob(encode));
                    imgs.add(img);
                    //file.delete();
                }
            }
            prod.setNombre((String) hm.get("nombre"));
            prod.setProdNum((String) hm.get("prodNum"));
            prod.setDesc((String) hm.get("desc"));
            prod.setIva(Double.parseDouble((String) hm.get("iva")));
            prod.setPrecio(Double.parseDouble((String) hm.get("precio")));
            prod.setPiezas(Integer.parseInt((String) hm.get("piezas")));
            prod.setEstatus("A");
            prod.setImagenes(imgs);
            ProductoDAO prodDAO = new ProductoDAO();
            if (prodDAO.registraProducto(prod)) {
                message = "Exito";
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    response.sendRedirect("index.jsp");
}

From source file:productupdate.java

void getformdata() {
    try {/*  w  w w.  j  a  v  a  2 s . c  o m*/
        ServletContext x = this.getServletContext();
        String path = x.getRealPath("/images");

        System.out.println(path + " path");
        DiskFileUpload p = new DiskFileUpload();
        List q = p.parseRequest(request);
        Iterator z = q.iterator();
        while (z.hasNext()) {
            FileItem f = (FileItem) z.next();
            if (f.isFormField() == true) {
                //non-file data

                String h = f.getFieldName();
                String data = f.getString();
                if (h.equalsIgnoreCase("productid")) {
                    productid = data;
                } else if (h.equalsIgnoreCase("productname")) {
                    productname = data;

                } else if (h.equalsIgnoreCase("category")) {
                    categoryid = data;
                } else if (h.equalsIgnoreCase("price")) {
                    price = data;
                } else if (h.equalsIgnoreCase("description")) {
                    description = data;
                } else if (h.equalsIgnoreCase("status")) {
                    System.out.println("status " + status);
                    status = data;
                }
            } else {
                //file data
                String filename = f.getName();
                if (filename != null && filename.length() > 0) {
                    File g = new File(filename);

                    filename = g.getName();

                    //creating unique file name
                    long w = System.currentTimeMillis();
                    filename = w + filename;
                    System.out.println("path " + path + " file " + filename);
                    //upload file
                    File t = new File(path, filename);
                    f.write(t);
                    if (f.getFieldName().equals("image")) {
                        System.out.println("images " + image);
                        image = filename;
                    }
                }

            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.threecrickets.prudence.util.FormWithFiles.java

/**
 * Constructor.//from  w  ww  .  j  av a  2 s.com
 * 
 * @param webForm
 *        The URL encoded web form
 * @param fileItemFactory
 *        The file item factory
 * @throws ResourceException
 *         In case of an upload handling error
 */
public FormWithFiles(Representation webForm, FileItemFactory fileItemFactory) throws ResourceException {
    if (webForm.getMediaType().includes(MediaType.MULTIPART_FORM_DATA)) {
        RestletFileUpload fileUpload = new RestletFileUpload(fileItemFactory);

        try {
            for (FileItem fileItem : fileUpload.parseRepresentation(webForm)) {
                Parameter parameter;
                if (fileItem.isFormField())
                    parameter = new Parameter(fileItem.getFieldName(), fileItem.getString());
                else {
                    if (fileItem instanceof DiskFileItem) {
                        File file = ((DiskFileItem) fileItem).getStoreLocation();
                        if (file == null)
                            // In memory
                            parameter = new FileParameter(fileItem.getFieldName(), fileItem.get(),
                                    fileItem.getContentType(), fileItem.getSize());
                        else
                            // On disk
                            parameter = new FileParameter(fileItem.getFieldName(), file,
                                    fileItem.getContentType(), fileItem.getSize());
                    } else
                        // Non-file form item
                        parameter = new Parameter(fileItem.getFieldName(), fileItem.getString());
                }

                add(parameter);
            }
        } catch (FileUploadException x) {
            throw new ResourceException(x);
        }
    } else {
        // Default parsing
        addAll(new Form(webForm));
    }
}

From source file:adminpackage.adminview.ProductAddition.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, Exception {
    response.setContentType("text/plain;charset=UTF-8");

    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);

    AdminViewProduct product = new AdminViewProduct();
    List<FileItem> items = upload.parseRequest(request);
    Iterator itr = items.iterator();
    String value = "defa";
    String url = "";
    while (itr.hasNext()) {
        FileItem item = (FileItem) itr.next();
        if (item.isFormField()) {
            String name = item.getFieldName();
            value = item.getString();
            switch (name) {
            case "pname":
                product.setName(value);//from   ww  w .java 2s .  c om
                break;
            case "quantity":
                product.setQuantity(Integer.parseInt(value));
                break;
            case "author":
                product.setAuthor(value);
                break;
            case "isbn":
                product.setISBN(Long.parseLong(value));
                break;
            case "description":
                product.setDescription(value);
                break;
            case "category":
                product.setCategory(value);
                break;
            case "price":
                product.setPrice(Integer.parseInt(value));
                break;
            }
        } else {

            //System.out.println(context.getRealPath("/pages/images/").replaceAll("\\\\target\\\\MavenOnlineShoping-1.0-SNAPSHOT", "\\\\src\\\\main\\\\webapp") + item.getName());
            //url = context.getRealPath("/pages/images/").replaceAll("\\\\target\\\\MavenOnlineShoping-1.0-SNAPSHOT", "\\\\src\\\\main\\\\webapp") + item.getName();
            UUID idOne = UUID.randomUUID();
            product.setImage(idOne.toString() + item.getName().substring(item.getName().length() - 4));
            item.write(new File(context.getRealPath("/pages/images/")
                    .replaceAll("\\\\target\\\\MavenOnlineShoping-1.0-SNAPSHOT", "\\\\src\\\\main\\\\webapp")
                    + idOne.toString() + item.getName().substring(item.getName().length() - 4)));
        }
    }

    PrintWriter out = response.getWriter();

    if (adminFacadeHandler.addBook(product)) {
        out.print("true");
    } else {
        //out.println("false");
        out.print("false");
    }
}

From source file:com.ci6225.marketzone.servlet.seller.AddProductServlet.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 * response)/*from  w  w w.  j av a  2 s .com*/
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String name = null;
    String description = null;
    String unitPrice = null;
    String quantity = null;
    FileItem imageItem = null;

    // constructs the folder where uploaded file will be stored
    //String uploadFolder = getServletContext().getRealPath("") + "/productImages";
    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(5000 * 1024);
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(5000 * 1024);

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

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

            if (!item.isFormField()) {
                if (item.getFieldName().equals("productImage") && !item.getString().equals("")) {
                    imageItem = item;
                }
                System.out.println(item.getFieldName());
            } else {
                System.out.println(item.getFieldName() + " " + item.getString());
                if (item.getFieldName().equals("name")) {
                    name = item.getString();
                } else if (item.getFieldName().equals("description")) {
                    description = item.getString();
                } else if (item.getFieldName().equals("unitPrice")) {
                    unitPrice = item.getString();
                } else if (item.getFieldName().equals("quantity")) {
                    quantity = item.getString();
                }
            }
        }

    } catch (FileUploadException ex) {
        System.out.println(ex);
        ex.printStackTrace();
        response.sendRedirect("./addProduct");
    } catch (Exception ex) {
        System.out.println(ex);
        ex.printStackTrace();
        response.sendRedirect("./addProduct");
    }

    FormValidation validation = new FormValidation();
    List<String> messageList = new ArrayList<String>();
    if (!validation.validateAddProduct(name, description, quantity, unitPrice, imageItem)) {
        messageList.addAll(validation.getErrorMessages());
        request.setAttribute("errorMessage", messageList);
        request.setAttribute("name", name);
        request.setAttribute("description", description);
        request.setAttribute("quantity", quantity);
        request.setAttribute("unitPrice", unitPrice);
        RequestDispatcher rd = request.getRequestDispatcher("./addProduct");
        rd.forward(request, response);
    }

    try {
        User user = (User) request.getSession().getAttribute("user");
        productBean.addProduct(name, description, user.getUserId(), Integer.parseInt(quantity),
                Float.parseFloat(unitPrice), imageItem);
        messageList.add("Product Added Successfully.");
        request.setAttribute("successMessage", messageList);
        RequestDispatcher rd = request.getRequestDispatcher("./ViewProductList");
        rd.forward(request, response);
    } catch (Exception e) {
        e.printStackTrace();
        response.sendRedirect("./addProduct");
    }
}

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 w w w.  j a  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
 */
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);
    }

}

From source file:com.shyshlav.functions.filework.download_image.java

public String download(HttpServletRequest request, HttpServletResponse response) throws IOException {
    request.setCharacterEncoding("UTF-8"); //  
    response.setCharacterEncoding("UTF-8");
    filePath = request.getSession().getServletContext().getInitParameter("avathars");
    System.out.println(filePath);
    isMultipart = ServletFileUpload.isMultipartContent(request);
    System.out.println(isMultipart);
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    if (!isMultipart) {
        return "  ";
    }/*from   w w w. j a  v  a2 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("c:\test"));
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("UTF-8");
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);
    try {
        // Parse the request to get file items.
        List<FileItem> fileItems = upload.parseRequest(request);
        // Process the uploaded file items
        Iterator i = fileItems.iterator();
        //String name,String password,String email,String surname,String link_to_image,String about_me,String id
        String name = null;
        String password = null;
        String re_password = null;
        String surname = null;
        String about_me = null;
        String id = null;
        String link_to_server = null;
        String email = null;
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (fi.isFormField()) {
                String fieldname = fi.getFieldName();
                String fieldvalue = fi.getString();
                if (fieldname.equals("name")) {
                    name = fi.getString("UTF-8");
                } else if (fieldname.equals("surname")) {
                    surname = fi.getString("UTF-8");
                } else if (fieldname.equals("password")) {
                    password = fi.getString("UTF-8");
                } else if (fieldname.equals("re_password")) {
                    re_password = fi.getString("UTF-8");
                } else if (fieldname.equals("about_me")) {
                    about_me = fi.getString("UTF-8");
                } else if (fieldname.equals("id")) {
                    id = fi.getString("UTF-8");
                } else if (fieldname.equals("email")) {
                    email = fi.getString("UTF-8");
                }
                System.out.println(fieldname + fieldvalue);
                if (fieldname == null || fieldvalue == null) {
                    return "? ? ? ";
                }
            }
            if (!fi.isFormField()) {
                if (!password.equals(re_password)) {
                    System.out.println(password + " - " + re_password);
                    return "  ?";
                }
                // Get the uploaded file parameters
                String fileName = email + ".png";
                link_to_server = "/musicbox/avathars/" + email + ".png".trim();
                // 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);
                System.out.println("Uploaded Filename: " + filePath + fileName);
            }
        }
        System.out.println(link_to_server);
        updateUser um = new updateUser();
        um.updateUser(name, password, surname, link_to_server, about_me, id);
    } catch (Exception ex) {
        System.out.println(ex);
        return "    1 ";
    }
    return "ok";
}

From source file:com.duroty.application.files.actions.UploadAction.java

protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    ActionMessages errors = new ActionMessages();

    try {//from w  ww .  j  a v a  2 s.c o m
        boolean isMultipart = FileUpload.isMultipartContent(request);

        Store storeInstance = getStoreInstance(request);

        if (isMultipart) {
            Map fields = new HashMap();
            Vector files = new Vector();

            //Parse the request
            List items = diskFileUpload.parseRequest(request);

            //Process the uploaded items
            Iterator iter = items.iterator();

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

                if (item.isFormField()) {
                    fields.put(item.getFieldName(), item.getString());
                } else {
                    if (!StringUtils.isBlank(item.getName())) {
                        ByteArrayOutputStream baos = null;

                        try {
                            baos = new ByteArrayOutputStream();

                            IOUtils.copy(item.getInputStream(), baos);

                            MailPartObj part = new MailPartObj();
                            part.setAttachent(baos.toByteArray());
                            part.setContentType(item.getContentType());
                            part.setName(item.getName());
                            part.setSize(item.getSize());

                            files.addElement(part);
                        } catch (Exception ex) {
                        } finally {
                            IOUtils.closeQuietly(baos);
                        }
                    }
                }
            }

            if (files.size() > 0) {
                //Integer label = new Integer((String) fields.get("label"));
                storeInstance.send(files, 0, Charset.defaultCharset().displayName());
            }
        } else {
            errors.add("general",
                    new ActionMessage(ExceptionCode.ERROR_MESSAGES_PREFIX + "mail.send", "The form is null"));
            request.setAttribute("exception", "The form is null");
            request.setAttribute("newLocation", null);
            doTrace(request, DLog.ERROR, getClass(), "The form is null");
        }
    } catch (Exception ex) {
        String errorMessage = ExceptionUtilities.parseMessage(ex);

        if (errorMessage == null) {
            errorMessage = "NullPointerException";
        }

        errors.add("general", new ActionMessage(ExceptionCode.ERROR_MESSAGES_PREFIX + "general", errorMessage));
        request.setAttribute("exception", errorMessage);
        doTrace(request, DLog.ERROR, getClass(), errorMessage);
    } finally {
    }

    if (errors.isEmpty()) {
        doTrace(request, DLog.INFO, getClass(), "OK");

        return mapping.findForward(Constants.ACTION_SUCCESS_FORWARD);
    } else {
        saveErrors(request, errors);

        return mapping.findForward(Constants.ACTION_FAIL_FORWARD);
    }
}

From source file:com.mingsoft.basic.servlet.UploadServlet.java

/**
 * ?post//www .  ja  v a  2  s  . c o  m
 * @param req HttpServletRequest
 * @param res HttpServletResponse 
 * @throws ServletException ?
 * @throws IOException ?
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    res.setContentType("text/html;charset=utf-8");
    PrintWriter out = res.getWriter();
    String uploadPath = this.getServletContext().getRealPath(File.separator); // 
    String isRename = "";// ???? true:???
    String _tempPath = req.getServletContext().getRealPath(File.separator) + "temp";//
    FileUtil.createFolder(_tempPath);
    File tempPath = new File(_tempPath); // 

    int maxSize = 1000000; // ??,?? 1000000/1024=0.9M
    //String allowedFile = ".jpg,.gif,.png,.zip"; // ?
    String deniedFile = ".exe,.com,.cgi,.asp"; // ??

    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    // ?????
    factory.setSizeThreshold(4096);
    // the location for saving data that is larger than getSizeThreshold()
    // ?SizeThreshold?
    factory.setRepository(tempPath);

    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum size before a FileUploadException will be thrown

    try {
        List fileItems = upload.parseRequest(req);

        Iterator iter = fileItems.iterator();

        // ????
        String regExp = ".+\\\\(.+)$";

        // 
        String[] errorType = deniedFile.split(",");
        Pattern p = Pattern.compile(regExp);
        String outPath = ""; //??
        while (iter.hasNext()) {

            FileItem item = (FileItem) iter.next();
            if (item.getFieldName().equals("uploadPath")) {
                outPath += item.getString();
                uploadPath += outPath;
            } else if (item.getFieldName().equals("isRename")) {
                isRename = item.getString();
            } else if (item.getFieldName().equals("maxSize")) {
                maxSize = Integer.parseInt(item.getString()) * 1048576;
            } else if (item.getFieldName().equals("allowedFile")) {
                //               allowedFile = item.getString();
            } else if (item.getFieldName().equals("deniedFile")) {
                deniedFile = item.getString();
            } else if (!item.isFormField()) { // ???
                String name = item.getName();
                long size = item.getSize();
                if ((name == null || name.equals("")) && size == 0)
                    continue;
                try {
                    // ?? 1000000/1024=0.9M
                    upload.setSizeMax(maxSize);

                    // ?
                    // ?
                    String fileName = System.currentTimeMillis() + name.substring(name.indexOf("."));
                    String savePath = uploadPath + File.separator;
                    FileUtil.createFolder(savePath);
                    // ???
                    if (StringUtil.isBlank(isRename) || Boolean.parseBoolean(isRename)) {
                        savePath += fileName;
                        outPath += fileName;
                    } else {
                        savePath += name;
                        outPath += name;
                    }
                    item.write(new File(savePath));
                    out.print(outPath.trim());
                    logger.debug("upload file ok return path " + outPath);
                    out.flush();
                    out.close();
                } catch (Exception e) {
                    this.logger.debug(e);
                }

            }
        }
    } catch (FileUploadException e) {
        this.logger.debug(e);
    }
}

From source file:com.cloudbees.plugins.deployer.JobConfigBuilderTest.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")) {
            CloudbeesDeployWarTest.assertOnArchive(fileItem.getInputStream());
        } else {/*from ww  w . j ava  2  s  .c o  m*/
            System.out.println(" item " + fileItem);
        }

    }

}