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:ar.com.easytech.faces.filters.MultipartRequest.java

@SuppressWarnings("unchecked")
public MultipartRequest(HttpServletRequest request, String path) throws Exception {
    super(request);
    DiskFileItemFactory factory = new DiskFileItemFactory();

    if (path != null)
        factory.setRepository(new File(path));

    ServletFileUpload upload = new ServletFileUpload(factory);
    parameterMap.put("path", path);

    try {//from   ww w .java 2 s  .  c  o m
        List<FileItem> items = (List<FileItem>) upload.parseRequest(request);

        for (FileItem item : items) {

            String str = item.getString();
            if (item.isFormField())
                parameterMap.put(item.getFieldName(), str);
            else {
                if (item.getName() != null) {
                    parameterMap.put("fileName", item.getName());
                }
                request.setAttribute(item.getFieldName(), item);
            }
        }

    } catch (FileUploadException ex) {
        ServletException servletEx = new ServletException();
        servletEx.initCause(ex);
        throw new Exception(ex.getLocalizedMessage());
    }
}

From source file:com.w4t.engine.requests.FileUploadRequest.java

public String getParameter(String name) {
    String result = null;/*from   w  w w .j  a  v  a 2s .co  m*/
    FileItem item = (FileItem) parameters.get(name);
    if (item != null && item.isFormField()) {
        result = item.getString();
    }
    return result;
}

From source file:com.zlfun.framework.excel.ExcelUtils.java

public static <T> List<T> httpInput(HttpServletRequest request, Class<T> clazz) {
    List<T> result = new ArrayList<T>();
    //??  /*w ww . jav  a 2  s  .  c  o m*/
    DiskFileItemFactory factory = new DiskFileItemFactory();
    //??  
    String path = request.getSession().getServletContext().getRealPath("/");
    factory.setRepository(new File(path));
    // ??   
    factory.setSizeThreshold(1024 * 1024);
    ServletFileUpload upload = new ServletFileUpload(factory);

    try {
        //?  
        List<FileItem> list = (List<FileItem>) upload.parseRequest(request);

        for (FileItem item : list) {
            //????  
            String name = item.getFieldName();

            //? ??  ?  
            if (item.isFormField()) {
                //? ??????   
                String value = item.getString();

                request.setAttribute(name, value);
            } //? ??    
            else {
                /**
                 * ?? ??
                 */
                //???  
                String value = item.getName();
                //????  

                fill(clazz, result, value, item.getInputStream());

                //??
            }
        }

    } catch (FileUploadException ex) {
        // TODO Auto-generated catch block      excel=null;
        Logger.getLogger(ExcelUtils.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {

        Logger.getLogger(ExcelUtils.class.getName()).log(Level.SEVERE, null, ex);
    }
    return result;
}

From source file:com.exilant.exility.core.HttpUtils.java

/***
 * Simplest way of handling files that are uploaded from form. Just put them
 * as name-value pair into service data. This is useful ONLY if the files
 * are reasonably small.//from   w w  w.  j a v a 2  s  .  c  om
 * 
 * @param req
 * @param data
 *            data in which
 */
public void simpleExtract(HttpServletRequest req, ServiceData data) {
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    try {
        /**
         * ServerFileUpload still deals with raw types. we have to have
         * workaround that
         */
        List<?> list = upload.parseRequest(req);
        if (list != null) {
            for (Object item : list) {
                if (item instanceof FileItem) {
                    FileItem fileItem = (FileItem) item;
                    data.addValue(fileItem.getFieldName(), fileItem.getString());
                } else {
                    Spit.out("Servlet Upload retruned an item that is not a FileItem. Ignorinig that");
                }
            }
        }
    } catch (FileUploadException e) {
        Spit.out(e);
        data.addError("Error while parsing form data. " + e.getMessage());
    }
}

From source file:com.globalsight.everest.webapp.pagehandler.administration.vendors.VendorHelper.java

/**
 * Save the request parameters from the CV/Resume page
 *///from www . j a va 2  s  .co  m
public static void saveCV(Vendor vendor, HttpServletRequest request) throws EnvoyServletException {
    // Create a new file upload handler
    DiskFileUpload upload = new DiskFileUpload();

    String radioValue = null;
    String resumeText = null;
    boolean doUpload = false;
    byte[] data = null;
    String filename = null;
    // Parse the request
    try {
        List /* FileItem */ items = upload.parseRequest(request);
        // Process the uploaded items
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()) {
                String name = item.getFieldName();
                String value = EditUtil.utf8ToUnicode(item.getString());
                if (name.equals("radioBtn")) {
                    radioValue = value;
                } else if (name.equals("resumeText")) {
                    resumeText = value;
                }
            } else {
                filename = item.getName();
                if (filename == null || filename.equals("")) {
                    // user hit done button but didn't modify the page
                    continue;
                } else {
                    doUpload = true;
                    data = item.get();
                }
            }
        }
        if (radioValue != null) {
            if (radioValue.equals("doc") && doUpload) {
                vendor.setResume(filename, data);
                try {
                    ServerProxy.getVendorManagement().saveResumeFile(vendor);
                } catch (Exception e) {
                    throw new EnvoyServletException(e);
                }
            } else if (radioValue.equals("text")) {
                vendor.setResume(resumeText);
            }
        }
    } catch (FileUploadException fe) {
        throw new EnvoyServletException(fe);
    }
}

From source file:attila.core.MultipartRequest.java

private void readTextParameter(FileItem item) throws UnsupportedEncodingException {
    byte[] bytes = item.getString().getBytes("ISO-8859-1");
    String name = item.getFieldName();
    String value = new String(bytes, getCharacterEncoding());
    addTextParameter(name, value);//from   w w w .j a  va2 s. co  m
}

From source file:com.cyclopsgroup.waterview.impl.servlet.MultipartServletRequestParameters.java

/**
 * Constructor for class MultipartServletRequestValueParser
 *
 * @param request Http request object//w  w w.ja  v  a 2 s . c  o  m
 * @param fileUpload File upload object
 * @throws FileUploadException Throw it out
 */
public MultipartServletRequestParameters(HttpServletRequest request, FileUploadBase fileUpload)
        throws FileUploadException {
    for (Object item : fileUpload.parseRequest(request)) {
        FileItem fileItem = (FileItem) item;
        if (fileItem.isFormField()) {
            add(fileItem.getFieldName(), fileItem.getString());
        } else {
            List<FileItem> list = fileItems.get(fileItem.getFieldName());
            if (list == null) {
                list = new ArrayList<FileItem>();
                fileItems.put(fileItem.getFieldName(), list);
            }
            list.add(fileItem);
        }
    }
}

From source file:com.krawler.esp.servlets.deskeramob.java

public static String createProject(Connection conn, HttpServletRequest request, String companyid,
        String subdomain, String userid) throws ServiceException {
    String status = "";
    DiskFileUpload fu = new DiskFileUpload();
    java.util.List fileItems = null;
    PreparedStatement pstmt = null;
    String imageName = "";
    try {//w w  w.  j a v  a  2 s  . c  o m
        fileItems = fu.parseRequest(request);
    } catch (FileUploadException e) {
        throw ServiceException.FAILURE("Admin.createProject", e);
    }

    java.util.HashMap arrParam = new java.util.HashMap();
    java.util.Iterator k = null;
    for (k = fileItems.iterator(); k.hasNext();) {
        FileItem fi1 = (FileItem) k.next();
        arrParam.put(fi1.getFieldName(), fi1.getString());
    }
    try {
        pstmt = conn
                .prepareStatement("select count(projectid) from project where companyid =? AND archived = 0");
        pstmt.setString(1, companyid);
        ResultSet rs = pstmt.executeQuery();
        int noProjects = 0;
        int maxProjects = 0;
        if (rs.next()) {
            noProjects = rs.getInt(1);
        }
        pstmt = conn.prepareStatement("select maxprojects from company where companyid =?");
        pstmt.setString(1, companyid);
        rs = pstmt.executeQuery();
        if (rs.next()) {
            maxProjects = rs.getInt(1);
        }
        if (noProjects == maxProjects) {
            return "The maximum limit for projects for this company has already reached";
        }
    } catch (SQLException e) {
        throw ServiceException.FAILURE("ProfileHandler.getPersonalInfo", e);
    }
    try {
        String projectid = UUID.randomUUID().toString();
        String projName = StringUtil.serverHTMLStripper(arrParam.get("projectname").toString()
                .replaceAll("[^\\w|\\s|'|\\-|\\[|\\]|\\(|\\)]", "").trim());
        String nickName = AdminServlet.makeNickName(conn, projName, 1);
        if (StringUtil.isNullOrEmpty(projName)) {
            status = "failure";
        } else {
            String qry = "INSERT INTO project (projectid,projectname,description,image,companyid, nickname) VALUES (?,?,?,?,?,?)";
            pstmt = conn.prepareStatement(qry);
            pstmt.setString(1, projectid);
            pstmt.setString(2, projName);
            pstmt.setString(3, arrParam.get("aboutproject").toString());
            pstmt.setString(4, imageName);
            pstmt.setString(5, companyid);
            pstmt.setString(6, nickName);
            int df = pstmt.executeUpdate();
            if (df != 0) {
                pstmt = conn.prepareStatement(
                        "INSERT INTO projectmembers (projectid, userid, status, inuseflag, planpermission) "
                                + "VALUES (?, ?, ?, ?, ?)");
                pstmt.setString(1, projectid);
                pstmt.setString(2, userid);
                pstmt.setInt(3, 4);
                pstmt.setBoolean(4, true);
                pstmt.setInt(5, 0);
                pstmt.executeUpdate();
            }
            //                        /DbUtil.executeUpdate(conn,qry,new Object[] { projectid,projName,arrParam.get("aboutproject"), imageName,companyid, nickName});
            if (arrParam.get("image").toString().length() != 0) {
                genericFileUpload uploader = new genericFileUpload();
                uploader.doPost(fileItems, projectid, StorageHandler.GetProfileImgStorePath());
                if (uploader.isUploaded()) {
                    pstmt = null;
                    //                                        DbUtil.executeUpdate(conn,
                    //                                                        "update project set image=? where projectid = ?",
                    //                                                        new Object[] {
                    //                                                                        ProfileImageServlet.ImgBasePath + projectid
                    //                                                                                        + uploader.getExt(), projectid });

                    pstmt = conn.prepareStatement("update project set image=? where projectid = ?");
                    pstmt.setString(1, ProfileImageServlet.ImgBasePath + projectid + uploader.getExt());
                    pstmt.setString(2, projectid);
                    pstmt.executeUpdate();
                    imageName = projectid + uploader.getExt();
                }
            }
            com.krawler.esp.handlers.Forum.setStatusProject(conn, userid, projectid, 4, 0, "", subdomain);
            status = "success";
            AdminServlet.setDefaultWorkWeek(conn, projectid);
            conn.commit();
        }
    } catch (ConfigurationException e) {
        status = "failure";
        throw ServiceException.FAILURE("Admin.createProject", e);
    } catch (SQLException e) {
        status = "failure";
        throw ServiceException.FAILURE("Admin.createProject", e);
    }
    return status;
}

From source file:ju.ehealthservice.images.SaveImage.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* w  w w  .  j a  v  a  2s .co  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/plain");
    response.setCharacterEncoding("UTF-8");
    PrintWriter out = response.getWriter();
    String ajaxUpdateResult = "";
    try {
        /* TODO output your page here. You may use following sample code. */
        ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
        List<FileItem> items = upload.parseRequest(request);
        String fileName = "";
        for (FileItem item : items) {
            if (item.isFormField()) {
                fileName = item.getString();
            } else {
                String filePath = Constants.IMAGE_REPOSITORY_PATH + fileName + ".jpg";
                File storeFile = new File(filePath);
                metadata.getData(fileName);
                metadata.updateImage(true);
                item.write(storeFile);
            }
        }
        ajaxUpdateResult = "true";
    } catch (FileUploadException ex) {
        ex.printStackTrace();
        ajaxUpdateResult = "false";
    } catch (Exception ex) {
        ex.printStackTrace();
        ajaxUpdateResult = "false";
    }
    out.print(ajaxUpdateResult);
}

From source file:br.com.SGIURD.utils.FileUploadWrapper.java

private void addSingleValueItem(FileItem aItem) {
    List<String> list = new ArrayList();
    list.add(aItem.getString());
    fRegularParams.put(aItem.getFieldName(), list);
}