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:net.mymam.upload.UploadMultipartRequestWrapper.java

public UploadMultipartRequestWrapper(HttpServletRequest request, ServletFileUpload upload)
        throws ServletException {
    super(request);
    try {//from  w ww  .  j a  v a2s.  c o m
        List fileItems = upload.parseRequest(request);
        for (int i = 0; i < fileItems.size(); i++) {
            FileItem item = (FileItem) fileItems.get(i);
            if (item.isFormField()) {
                addParameter(item.getFieldName(), item.getString(), formParameters);
            } else {
                addParameter(item.getFieldName(), item, fileParameters);
            }
        }
    } catch (FileUploadException e) {
        // Request timed out
        ServletException servletException = new ServletException();
        servletException.initCause(e);
        throw servletException;
    }
}

From source file:by.creepid.jsf.fileupload.UploadFilter.java

private void processFormField(FileItem formField, Map<String, String[]> parameterMap) {

    String name = formField.getFieldName();
    String value = formField.getString();
    String[] values = parameterMap.get(name);

    if (values == null) {
        // Not in parameter map yet, so add as new value.
        parameterMap.put(name, new String[] { value });
    } else {/*from   w ww  .j  ava 2 s.  co m*/
        // Multiple field values, so add new value to existing array.
        int length = values.length;
        String[] newValues = new String[length + 1];

        System.arraycopy(values, 0, newValues, 0, length);

        newValues[length] = value;
        parameterMap.put(name, newValues);
    }
}

From source file:com.github.ikidou.handler.FormHandler.java

private List<FileEntity> getFileEntities(Map<String, Object> result, List<FileItem> fileItems)
        throws Exception {
    List<FileEntity> fileEntities = new ArrayList<>();

    for (FileItem fileItem : fileItems) {

        if (fileItem.isFormField()) {
            fileItem.getFieldName();/*from  w ww  .  jav a  2 s. c  o  m*/
            result.put(fileItem.getFieldName(), fileItem.getString());
            if (!fileItem.isInMemory()) {
                fileItem.delete();
            }
        } else {
            FileEntity fileEntity = new FileEntity();
            fileEntity.name = fileItem.getName();
            fileEntity.contentType = fileItem.getContentType();
            fileEntity.size = fileItem.getSize();
            fileEntity.readableSize = FileSizeUtil.toReadable(fileItem.getSize());
            fileEntity.savePath = "Data/" + fileEntity.name;
            File file = new File(fileEntity.savePath);
            fileItem.write(file);
            fileEntities.add(fileEntity);
        }

    }

    return fileEntities;
}

From source file:inet.common.jsf.request.MultipartRequest.java

private String getItemString(FileItem item) {
    try {/*from w w w .  j  a v a 2 s. com*/
        String characterEncoding = "UTF-8";
        return (characterEncoding == null) ? item.getString() : item.getString(characterEncoding);
    } catch (UnsupportedEncodingException e) {
        logger.severe("Unsupported character encoding " + getRequest().getCharacterEncoding());
        return item.getString();
    }
}

From source file:gwtupload.sendmailsample.server.SendMailSampleServlet.java

@Override
public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles)
        throws UploadActionException {
    try {/*www . java 2  s  . c  om*/
        String from = null, to = null, subject = "", body = "";
        // create a new multipart content
        MimeMultipart multiPart = new MimeMultipart();
        for (FileItem item : sessionFiles) {
            if (item.isFormField()) {
                if ("from".equals(item.getFieldName()))
                    from = item.getString();
                if ("to".equals(item.getFieldName()))
                    to = item.getString();
                if ("subject".equals(item.getFieldName()))
                    subject = item.getString();
                if ("body".equals(item.getFieldName()))
                    body = item.getString();
            } else {
                // add the file part to multipart content
                MimeBodyPart part = new MimeBodyPart();
                part.setFileName(item.getName());
                part.setDataHandler(
                        new DataHandler(new ByteArrayDataSource(item.get(), item.getContentType())));
                multiPart.addBodyPart(part);
            }
        }

        // add the text part to multipart content
        MimeBodyPart txtPart = new MimeBodyPart();
        txtPart.setContent(body, "text/plain");
        multiPart.addBodyPart(txtPart);

        // configure smtp server
        Properties props = System.getProperties();
        props.put("mail.smtp.host", SMTP_SERVER);
        // create a new mail session and the mime message
        MimeMessage mime = new MimeMessage(Session.getInstance(props));
        mime.setText(body);
        mime.setContent(multiPart);
        mime.setSubject(subject);
        mime.setFrom(new InternetAddress(from));
        for (String rcpt : to.split("[\\s;,]+"))
            mime.addRecipient(Message.RecipientType.TO, new InternetAddress(rcpt));
        // send the message
        Transport.send(mime);
    } catch (MessagingException e) {
        throw new UploadActionException(e.getMessage());
    }
    return "Your mail has been sent successfuly.";
}

From source file:com.surevine.alfresco.audit.listeners.PerishableUploadDocumentAuditEventListener.java

@Override
protected void populateSecondaryAuditItems(List<Auditable> events, HttpServletRequest request,
        HttpServletResponse response, JSONObject postContent) throws JSONException {
    // Create a ServletFileUpload instance to parse the form
    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
    upload.setHeaderEncoding("UTF-8");

    if (ServletFileUpload.isMultipartContent(request)) {
        try {/*  w  w w . jav  a2s  .c o  m*/
            String perishableReason = null;
            String tags = null;

            for (final Object o : upload.parseRequest(request)) {
                FileItem item = (FileItem) o;

                if (item.isFormField() && "perishable".equals(item.getFieldName())) {
                    perishableReason = item.getString();
                } else if (item.isFormField() && "tags".equals(item.getFieldName())) {
                    tags = item.getString();
                }
            }

            Auditable primaryEvent = events.get(0);

            // If this is a site with perish reasons configured...
            if (_perishabilityLogic.getPerishReasons(primaryEvent.getSite()).size() > 0) {
                AuditItem item = new AuditItem();

                setGenericAuditMetadata(item, request);

                // Copy any relevant fields from the primary audit event
                item.setNodeRef(primaryEvent.getNodeRef());
                item.setVersion(primaryEvent.getVersion());
                item.setSecLabel(primaryEvent.getSecLabel());
                item.setSource(primaryEvent.getSource());

                item.setAction(MarkPerishableAuditEventListener.ACTION);

                if (!StringUtils.isBlank(perishableReason)) {
                    item.setDetails(perishableReason);
                } else {
                    item.setDetails(MarkPerishableAuditEventListener.NO_PERISHABLE_MARK);
                }

                if (tags != null) {
                    item.setTags(StringUtils.join(tags.trim().split(" "), ','));
                }

                events.add(item);
            }
        } catch (FileUploadException e) {
            logger.error("Error while parsing request form", e);
        }
    }
}

From source file:Controller.ControllerImageCustomerIndex.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from  w ww.j av  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
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    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 (Exception e) {
            e.printStackTrace();
        }
        Iterator iter = items.iterator();
        Hashtable params = new Hashtable();
        String fileName = null;
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()) {
                params.put(item.getFieldName(), item.getString());
            } else {

                try {
                    String itemName = item.getName();
                    fileName = itemName.substring(itemName.lastIndexOf("\\") + 1);
                    System.out.println("path" + fileName);
                    String RealPath = getServletContext().getRealPath("/") + "upload\\" + fileName;
                    System.out.println("Rpath" + RealPath);
                    File savedFile = new File(RealPath);
                    item.write(savedFile);
                    String username = (String) params.get("txtusername");
                    String password = (String) params.get("txpassword");
                    String hoten = (String) params.get("txthoten");
                    String gioitinh = (String) params.get("txtgioitinh");
                    String email = (String) params.get("txtemail");
                    String role = "false";
                    Customer cus = new Customer(username, password, hoten, gioitinh, email, role,
                            "upload\\" + fileName);

                    CustomerDAO.ThemKhachHang(cus);
                    RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
                    rd.forward(request, response);
                } 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();
        }/*from w w  w  .jav  a  2s .c  om*/
    }
    return null;
}

From source file:com.liteoc.bean.rule.FileUploadHelper.java

@SuppressWarnings("unchecked")
private List<File> getFiles(HttpServletRequest request, ServletContext context,
        String dirToSaveUploadedFileIn) {
    List<File> files = new ArrayList<File>();

    // FileCleaningTracker fileCleaningTracker =
    // FileCleanerCleanup.getFileCleaningTracker(context);

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

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(getFileProperties().getFileSizeMax());
    try {/*  w ww  .j  av a 2  s  . co  m*/
        // Parse the request
        List<FileItem> items = upload.parseRequest(request);
        // Process the uploaded items

        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();

            if (item.isFormField()) {
                request.setAttribute(item.getFieldName(), item.getString());
                // DO NOTHING , THIS SHOULD NOT BE Handled here
            } else {
                getFileProperties().isValidExtension(item.getName());
                files.add(processUploadedFile(item, dirToSaveUploadedFileIn));

            }
        }
        return files;
    } catch (FileSizeLimitExceededException slee) {
        throw new OpenClinicaSystemException("exceeds_permitted_file_size",
                new Object[] { String.valueOf(getFileProperties().getFileSizeMaxInMb()) }, slee.getMessage());
    } catch (FileUploadException fue) {
        throw new OpenClinicaSystemException("file_upload_error_occured", new Object[] { fue.getMessage() },
                fue.getMessage());
    }
}

From source file:Controller.ControllerImageCustomer.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from w  w  w .ja va2s  .  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 {
    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 (Exception e) {
            e.printStackTrace();
        }
        Iterator iter = items.iterator();
        Hashtable params = new Hashtable();
        String fileName = null;
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()) {
                params.put(item.getFieldName(), item.getString());
            } else {

                try {
                    String itemName = item.getName();
                    fileName = itemName.substring(itemName.lastIndexOf("\\") + 1);
                    System.out.println("path" + fileName);
                    String RealPath = getServletContext().getRealPath("/") + "upload\\" + fileName;
                    System.out.println("Rpath" + RealPath);
                    File savedFile = new File(RealPath);
                    item.write(savedFile);
                    String username = (String) params.get("txtusername");
                    String password = (String) params.get("txpassword");
                    String hoten = (String) params.get("txthoten");
                    String gioitinh = (String) params.get("txtgioitinh");
                    String email = (String) params.get("txtemail");
                    String role = "false";
                    String Register = (String) params.get("Register");
                    String url = "CustomerDao.jsp";
                    if (Register.equals("Register")) {
                        url = "index.jsp";
                    }
                    Customer cus = new Customer(username, password, hoten, gioitinh, email, role,
                            "upload\\" + fileName);
                    CustomerDAO.ThemKhachHang(cus);
                    RequestDispatcher rd = request.getRequestDispatcher(url);
                    rd.forward(request, response);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }

    }

}