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:com.silverpeas.form.form.XmlSearchForm.java

private String getParameterValue(List<FileItem> items, String parameterName) {
    SilverTrace.debug("form", "XmlSearchForm.getParameterValue", "root.MSG_GEN_ENTER_METHOD",
            "parameterName = " + parameterName);
    FileItem item = getParameter(items, parameterName);
    if (item != null && item.isFormField()) {
        SilverTrace.debug("form", "XmlSearchForm.getParameterValue", "root.MSG_GEN_EXIT_METHOD",
                "parameterValue = " + item.getString());
        return item.getString();
    }//ww  w  .  j av  a 2s.co  m
    return null;
}

From source file:com.krawler.esp.portalmsg.Forum.java

public static String insertForumPost(Connection conn, HttpServletRequest request)
        throws ServiceException, ParseException, JSONException {
    org.apache.commons.fileupload.DiskFileUpload fu = new org.apache.commons.fileupload.DiskFileUpload();
    java.util.List fileItems = null;
    org.apache.commons.fileupload.FileItem fi = null;
    int sizeinmb = forummsgcomm.getmaxfilesize(conn, AuthHandler.getCompanyid(request, false));
    long maxsize = sizeinmb * 1024 * 1024;
    boolean fileupload = false;
    fu.setSizeMax(maxsize);//from   w w w . j  ava 2s  .com
    java.util.HashMap arrParam = new java.util.HashMap();
    JSONObject jobj = new JSONObject();
    try {
        fileItems = fu.parseRequest(request);
    } catch (org.apache.commons.fileupload.FileUploadException e) {
        com.krawler.utils.json.base.JSONObject jerrtemp = new com.krawler.utils.json.base.JSONObject();
        jerrtemp.put("Success", "Fail");
        jerrtemp.put("msg", "Problem while uploading file.");
        jobj.append("data", jerrtemp);
        return jobj.toString();
    }
    for (java.util.Iterator k = fileItems.iterator(); k.hasNext();) {
        fi = (org.apache.commons.fileupload.FileItem) k.next();
        arrParam.put(fi.getFieldName(), fi.getString());
        if (!fi.isFormField()) {
            if (fi.getSize() > maxsize) {
                com.krawler.utils.json.base.JSONObject jerrtemp = new com.krawler.utils.json.base.JSONObject();
                jerrtemp.put("Success", "Fail");
                jerrtemp.put("msg", "For attachments, maximum file size allowed is " + sizeinmb + " MB");
                jobj.append("data", jerrtemp);
                return jobj.toString();
            }
            fileupload = true;
        }
    }
    //                destinationDirectory = com.krawler.esp.handlers.StorageHandler
    //               .GetDocStorePath()
    int firstReply = Integer.parseInt(request.getParameter("firstReply"));
    String ptext = java.net.URLDecoder.decode(arrParam.get("ptxt").toString());
    String repto = request.getParameter("repto");
    String title = java.net.URLDecoder.decode(arrParam.get("title").toString());
    String u_id = request.getParameter("userId");
    String group_id = request.getParameter("groupId");
    DbResults rs = null;
    DbResults rs1 = null;
    DbResults rs2 = null;
    String post_id = UUID.randomUUID().toString();
    String topic_id = "1";
    String topic_title = null;
    String dateTime = null;
    String UserName = null;
    String Image = null;
    String query = null;
    JSONStringer j = new JSONStringer();

    String temp = null;
    title = StringUtil.serverHTMLStripper(title);

    group_id = StringUtil.serverHTMLStripper(group_id);
    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    java.util.Date d = new java.util.Date();
    java.sql.Timestamp sqlPostDate = new Timestamp(d.getTime());
    if (StringUtil.isNullOrEmpty(repto) /*|| StringUtil.isNullOrEmpty(title)*/ || StringUtil.isNullOrEmpty(u_id)
            || StringUtil.isNullOrEmpty(group_id)) {
        com.krawler.utils.json.base.JSONObject jerrtemp = new com.krawler.utils.json.base.JSONObject();
        jerrtemp.put("Success", "Fail");
        jobj.append("data", jerrtemp);
        return jobj.toString();
    }
    if (fileupload) {
        forummsgcomm.doPost(conn, fileItems, post_id, sqlPostDate, u_id, "");
    }
    if (firstReply == 0) {

        query = "INSERT INTO krawlerforum_topics(topic_id, group_id, topic_title, topic_poster, post_time, post_subject,post_text, ifread,flag) VALUES (?, ?, ?, ?, ?, ?,?, ?, ?)";
        DbUtil.executeUpdate(conn, query,
                new Object[] { post_id, group_id, title, u_id, sqlPostDate, ptext, ptext, false, false });

        post_id = "topic" + post_id;
    } else if (firstReply == 1) {
        repto = repto.substring(5);

        query = "INSERT INTO krawlerforum_posts(post_id, post_poster, topic_id, group_id, topic_title,post_time, post_subject, post_text, reply_to, flag, ifread,reply_to_post) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
        DbUtil.executeUpdate(conn, query, new Object[] { post_id, u_id, topic_id, group_id, topic_title,
                sqlPostDate, title, ptext, repto, false, false, "-999" });

        repto = "topic" + repto;
    } else if (firstReply == 2) {
        query = "INSERT INTO krawlerforum_posts(post_id, post_poster, topic_id, group_id, topic_title, post_time, post_subject, post_text, reply_to, flag, ifread,reply_to_post) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
        DbUtil.executeUpdate(conn, query, new Object[] { post_id, u_id, topic_id, group_id, topic_title,
                sqlPostDate, title, ptext, "1", false, false, repto });

    }

    query = "SELECT userlogin.username,image FROM users inner join userlogin on users.userid = userlogin.userid where users.userid=?;";
    rs2 = DbUtil.executeQuery(conn, query, u_id);

    if (rs2.next()) {
        UserName = (rs2.getString(1));
        Image = (rs2.getString(2));
    }
    String userTime = Timezone.toCompanyTimezone(conn, sqlPostDate.toString(),
            CompanyHandler.getCompanyByUser(conn, u_id));
    java.util.Date tempdate = sdf.parse(userTime);
    com.krawler.utils.json.base.JSONObject jtemp = new com.krawler.utils.json.base.JSONObject();
    jtemp.put("Success", "Success");
    jtemp.put("ID", post_id);
    jtemp.put("Subject", title);
    jtemp.put("Received", sdf.format(tempdate));
    jtemp.put("From", UserName);
    jtemp.put("Details", "");
    jtemp.put("Flag", "false");
    jtemp.put("Image", Image);
    jtemp.put("Parent", repto);
    jobj.append("data", jtemp);
    /*temp = j.object().key("Success").value("Success").key("ID").value(
    post_id).key("Subject").value(title).key("Received").value(
    sdf1.format(tempdate).toString()).key("From").value(UserName)
    .key("Details").value("").key("Flag").value("false").key(
    "Image").value(Image).key("Parent").value(repto)
    .endObject().toString();*/
    return jobj.toString();
}

From source file:com.orange.mmp.context.RequestContext.java

/**
 * HttpServletRequest getParameterMap delegation method
 * /*from   w  w w  .  j a  va  2 s.co m*/
 * @return A Map abstraction of parameters
 */
@SuppressWarnings("unchecked")
public Map getParameterMap() {
    if (!this.isMultipart)
        return this.httpServletRequest.getParameterMap();
    else if (this.multipartItems != null) {
        Map<String, String> parameterMap = new HashMap<String, String>();
        for (FileItem item : this.multipartItems) {
            if (item.isFormField())
                parameterMap.put(item.getFieldName(), item.getString());
        }
        return parameterMap;
    }
    return null;
}

From source file:com.orange.mmp.context.RequestContext.java

/**
 * HttpServletRequest getParameter delegation method
 * //  w  w  w .  j a  v  a  2 s  . c o m
 * @param name The name of the parameter to get
 * @return The value of the parameter
 */
public String getParameter(String name) {
    if (!this.isMultipart)
        return this.httpServletRequest.getParameter(name);
    else if (this.multipartItems != null) {
        for (FileItem item : this.multipartItems) {
            if (item.isFormField() && item.getFieldName().equals(name)) {
                return item.getString();
            }
        }
    }
    return null;
}

From source file:hu.ptemik.gallery.servlets.UploadServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession(false);
    User user = (User) session.getAttribute("user");
    String uploadFolder = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;

    if (ServletFileUpload.isMultipartContent(request) && user != null) {
        try {/*from w w w. j  a v  a 2  s .  c o m*/
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
            Picture pic = new Picture();
            File uploadedFile = null;

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    String filePath = uploadFolder + File.separator + fileName;
                    String relativePath = UPLOAD_DIRECTORY + "/" + fileName;

                    uploadedFile = new File(filePath);
                    item.write(uploadedFile);

                    pic.setUrl(relativePath);
                } else {
                    if (item.getFieldName().equals("title")) {
                        pic.setTitle(item.getString());
                    } else if (item.getFieldName().equals("description")) {
                        pic.setDescription(item.getString());
                    }
                }
            }

            if (Controller.newPicture(pic, user)) {
                request.setAttribute("successMessage", "A fjl feltltse sikerlt!");
            } else {
                FileUtils.deleteQuietly(uploadedFile);
                throw new Exception();
            }
        } catch (FileNotFoundException ex) {
            request.setAttribute("errorMessage", "Hinyzik a fjl!");
        } catch (Exception ex) {
            request.setAttribute("errorMessage", "Hiba a fjl feltltse sorn!");
        }
    } else {
        request.setAttribute("errorMessage", "Form hiba");
    }

    request.getRequestDispatcher("upload.jsp").forward(request, response);
}

From source file:com.ibm.btt.sample.SampleFileHandler.java

/**
 * NOTES: In this sample, we just handle the first file item in the upload request. 
 * //  w  w w.  ja va2 s.c om
 * @param request
 * @param fileItems upload file items
 * @return the first file item or null if errors 
 */
private FileItem getTheFileItem(HttpServletRequest request, List<FileItem> fileItems) {
    String name = "";
    for (FileItem fileItem : fileItems) {
        //common form item name
        name = fileItem.getFieldName();
        if (fileItem.isFormField()) {
            // common form item value 
            String value = fileItem.getString();
            if (LOG.doDebug()) {
                LOG.debug(new StringBuilder().append("Request item -- ").append(name).append(": ").append(value)
                        .toString());
            }
        } else {
            if (name == null || "".equals(name.trim())) {
                continue;
            }
            return fileItem;
        }
    }
    return null;
}

From source file:com.occamlab.te.web.TestServlet.java

public void processFormData(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    try {//from   www .j a v a  2  s.c  o  m
        FileItemFactory ffactory;
        ServletFileUpload upload;
        List /* FileItem */ items = null;
        HashMap<String, String> params = new HashMap<String, String>();
        boolean multipart = ServletFileUpload.isMultipartContent(request);
        if (multipart) {
            ffactory = new DiskFileItemFactory();
            upload = new ServletFileUpload(ffactory);
            items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField()) {
                    params.put(item.getFieldName(), item.getString());
                }
            }
        } else {
            Enumeration paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String name = (String) paramNames.nextElement();
                params.put(name, request.getParameter(name));
            }
        }
        HttpSession session = request.getSession();
        ServletOutputStream out = response.getOutputStream();
        String operation = params.get("te-operation");
        if (operation.equals("Test")) {
            TestSession s = new TestSession();
            String user = request.getRemoteUser();
            File logdir = new File(conf.getUsersDir(), user);
            String mode = params.get("mode");
            RuntimeOptions opts = new RuntimeOptions();
            opts.setWorkDir(conf.getWorkDir());
            opts.setLogDir(logdir);
            if (mode.equals("retest")) {
                opts.setMode(Test.RETEST_MODE);
                String sessionid = params.get("session");
                String test = params.get("test");
                if (sessionid == null) {
                    int i = test.indexOf("/");
                    sessionid = i > 0 ? test.substring(0, i) : test;
                }
                opts.setSessionId(sessionid);
                if (test == null) {
                    opts.addTestPath(sessionid);
                } else {
                    opts.addTestPath(test);
                }
                for (Entry<String, String> entry : params.entrySet()) {
                    if (entry.getKey().startsWith("profile_")) {
                        String profileId = entry.getValue();
                        int i = profileId.indexOf("}");
                        opts.addTestPath(sessionid + "/" + profileId.substring(i + 1));
                    }
                }
                s.load(logdir, sessionid);
                opts.setSourcesName(s.getSourcesName());
            } else if (mode.equals("resume")) {
                opts.setMode(Test.RESUME_MODE);
                String sessionid = params.get("session");
                opts.setSessionId(sessionid);
                s.load(logdir, sessionid);
                opts.setSourcesName(s.getSourcesName());
            } else {
                opts.setMode(Test.TEST_MODE);
                String sessionid = LogUtils.generateSessionId(logdir);
                s.setSessionId(sessionid);
                String sources = params.get("sources");
                s.setSourcesName(sources);
                SuiteEntry suite = conf.getSuites().get(sources);
                s.setSuiteName(suite.getId());
                //                    String suite = params.get("suite");
                //                    s.setSuiteName(suite);
                String description = params.get("description");
                s.setDescription(description);
                opts.setSessionId(sessionid);
                opts.setSourcesName(sources);
                opts.setSuiteName(suite.getId());
                ArrayList<String> profiles = new ArrayList<String>();
                for (Entry<String, String> entry : params.entrySet()) {
                    if (entry.getKey().startsWith("profile_")) {
                        profiles.add(entry.getValue());
                        opts.addProfile(entry.getValue());
                    }
                }
                s.setProfiles(profiles);
                s.save(logdir);
            }
            String webdir = conf.getWebDirs().get(s.getSourcesName());
            //                String requestURI = request.getRequestURI();
            //                String contextPath = requestURI.substring(0, requestURI.indexOf(request.getServletPath()) + 1);
            //                URI contextURI = new URI(request.getScheme(), null, request.getServerName(), request.getServerPort(), contextPath, null, null);
            URI contextURI = new URI(request.getScheme(), null, request.getServerName(),
                    request.getServerPort(), request.getRequestURI(), null, null);
            opts.setBaseURI(new URL(contextURI.toURL(), webdir + "/").toString());
            //                URI baseURI = new URL(contextURI.toURL(), webdir).toURI();
            //                String base = baseURI.toString() + URLEncoder.encode(webdir, "UTF-8") + "/";
            //                opts.setBaseURI(base);
            //System.out.println(opts.getSourcesName());
            TECore core = new TECore(engine, indexes.get(opts.getSourcesName()), opts);
            //System.out.println(indexes.get(opts.getSourcesName()).toString());
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PrintStream ps = new PrintStream(baos);
            core.setOut(ps);
            core.setWeb(true);
            Thread thread = new Thread(core);
            session.setAttribute("testsession", core);
            thread.start();
            response.setContentType("text/xml");
            out.println("<thread id=\"" + thread.getId() + "\" sessionId=\"" + s.getSessionId() + "\"/>");
        } else if (operation.equals("Stop")) {
            response.setContentType("text/xml");
            TECore core = (TECore) session.getAttribute("testsession");
            if (core != null) {
                core.stopThread();
                session.removeAttribute("testsession");
                out.println("<stopped/>");
            } else {
                out.println("<message>Could not retrieve core object</message>");
            }
        } else if (operation.equals("GetStatus")) {
            TECore core = (TECore) session.getAttribute("testsession");
            response.setContentType("text/xml");
            out.print("<status");
            if (core.getFormHtml() != null) {
                out.print(" form=\"true\"");
            }
            if (core.isThreadComplete()) {
                out.print(" complete=\"true\"");
                session.removeAttribute("testsession");
            }
            out.println(">");
            out.print("<![CDATA[");
            //                out.print(core.getOutput());
            out.print(URLEncoder.encode(core.getOutput(), "UTF-8").replace('+', ' '));
            out.println("]]>");
            out.println("</status>");
        } else if (operation.equals("GetForm")) {
            TECore core = (TECore) session.getAttribute("testsession");
            String html = core.getFormHtml();
            core.setFormHtml(null);
            response.setContentType("text/html");
            out.print(html);
        } else if (operation.equals("SubmitForm")) {
            TECore core = (TECore) session.getAttribute("testsession");
            Document doc = DB.newDocument();
            Element root = doc.createElement("values");
            doc.appendChild(root);
            for (String key : params.keySet()) {
                if (!key.startsWith("te-")) {
                    Element valueElement = doc.createElement("value");
                    valueElement.setAttribute("key", key);
                    valueElement.appendChild(doc.createTextNode(params.get(key)));
                    root.appendChild(valueElement);
                }
            }
            if (multipart) {
                Iterator iter = items.iterator();
                while (iter.hasNext()) {
                    FileItem item = (FileItem) iter.next();
                    if (!item.isFormField() && !item.getName().equals("")) {
                        File uploadedFile = new File(core.getLogDir(),
                                StringUtils.getFilenameFromString(item.getName()));
                        item.write(uploadedFile);
                        Element valueElement = doc.createElement("value");
                        String key = item.getFieldName();
                        valueElement.setAttribute("key", key);
                        if (core.getFormParsers().containsKey(key)) {
                            Element parser = core.getFormParsers().get(key);
                            URL url = uploadedFile.toURI().toURL();
                            Element resp = core.parse(url.openConnection(), parser, doc);
                            Element content = DomUtils.getElementByTagName(resp, "content");
                            if (content != null) {
                                Element child = DomUtils.getChildElement(content);
                                if (child != null) {
                                    valueElement.appendChild(child);
                                }
                            }
                        } else {
                            Element fileEntry = doc.createElementNS(CTL_NS, "file-entry");
                            fileEntry.setAttribute("full-path",
                                    uploadedFile.getAbsolutePath().replace('\\', '/'));
                            fileEntry.setAttribute("media-type", item.getContentType());
                            fileEntry.setAttribute("size", String.valueOf(item.getSize()));
                            valueElement.appendChild(fileEntry);
                        }
                        root.appendChild(valueElement);
                    }
                }
            }
            core.setFormResults(doc);
            response.setContentType("text/html");
            out.println("<html>");
            out.println("<head><title>Form Submitted</title></head>");
            out.print("<body onload=\"window.parent.update()\"></body>");
            out.println("</html>");
        }
    } catch (Throwable t) {
        throw new ServletException(t);
    }
}

From source file:com.yanzhenjie.andserver.sample.response.RequestUploadHandler.java

/**
 * Parse file and save./*from   w  w w.ja  v a2  s .  c  o m*/
 *
 * @param request       request.
 * @param saveDirectory save directory.
 * @throws Exception may be.
 */
private void processFileUpload(HttpRequest request, File saveDirectory) throws Exception {
    FileItemFactory factory = new DiskFileItemFactory(1024 * 1024, saveDirectory);
    HttpFileUpload fileUpload = new HttpFileUpload(factory);

    // Set upload process listener.
    // fileUpload.setProgressListener(new ProgressListener(){...});

    List<FileItem> fileItems = fileUpload
            .parseRequest(new HttpUploadContext((HttpEntityEnclosingRequest) request));

    for (FileItem fileItem : fileItems) {
        if (!fileItem.isFormField()) { // File param.
            // Attribute.
            // fileItem.getContentType();
            // fileItem.getFieldName();
            // fileItem.getName();
            // fileItem.getSize();
            // fileItem.getString();

            File uploadedFile = new File(saveDirectory, fileItem.getName());
            // ?
            fileItem.write(uploadedFile);
        } else { // General param.
            String key = fileItem.getName();
            String value = fileItem.getString();
        }
    }
}

From source file:Controllers.AddItem.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//w w w .j a v  a2s  . com
 * @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 = null;
    String itemCode = null;
    String price = null;
    String quantity = null;
    String category = null;
    String image = null;
    HttpSession session = request.getSession(true);
    User user = (User) session.getAttribute("user");
    if (user == null) {
        response.sendRedirect("login");
        return;
    }
    //        request.getServletContext().getRealPath("/uploads");
    String path = request.getServletContext().getRealPath("/uploads");
    System.out.println(path);

    if (ServletFileUpload.isMultipartContent(request)) {
        try {
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    //                        new File(path).mkdirs();
                    File directory = new File(path + File.separator + fileName);
                    image = fileName;
                    item.write(directory);
                } else {
                    if ("name".equals(item.getFieldName())) {
                        name = item.getString();
                    } else if ("itemCode".equals(item.getFieldName())) {
                        itemCode = item.getString();
                    } else if ("price".equals(item.getFieldName())) {
                        price = item.getString();
                    } else if ("quantity".equals(item.getFieldName())) {
                        quantity = item.getString();
                    } else if ("category".equals(item.getFieldName())) {
                        category = item.getString();
                    }
                }
            }

            //File uploaded successfully
            System.out.println("done");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    boolean status = ItemRepository.saveItem(name, itemCode, price, quantity, category, image, user);
    String message;
    if (status) {
        message = "Item saved successfully";
        response.sendRedirect("dashboard");
    } else {
        message = "Item not saved !!";
        request.setAttribute("message", message);
        request.getRequestDispatcher("dashboard/addItem.jsp").forward(request, response);
    }
}

From source file:de.jwi.jfm.servlets.Controller.java

private String handleUpload(HttpServletRequest request, Folder folder) throws Exception {
    DiskFileUpload upload = new DiskFileUpload();
    upload.setRepositoryPath(tempDir.toString());
    System.out.println(upload.getSizeMax());

    // parse this request by the handler
    // this gives us a list of items from the request
    List items = upload.parseRequest(request);

    Iterator itr = items.iterator();

    boolean unzip = false;

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

        // check if the current item is a form field or an uploaded file
        if (item.isFormField()) {
            String name = item.getFieldName();
            String value = item.getString();
            if ("command".equals(name) && "unzip".equals(value)) {
                unzip = true;/*  ww w. j a  v  a  2s . c  o m*/
            }
        } else {
            String name = item.getFieldName();
            unzip = "unzip".equals(name);

            if (!"".equals(item.getName())) {
                folder.upload(item, unzip);
            }
            // the item must be an uploaded file save it to disk. Note that
            // there
            // seems to be a bug in item.getName() as it returns the full
            // path on
            // the client's machine for the uploaded file name, instead of
            // the file
            // name only. To overcome that, I have used a workaround using
            // fullFile.getName().
            /*
             * File fullFile = new File(item.getName()); File savedFile =
             * new File(getServletContext().getRealPath("/"),
             */
            // item.write(savedFile);
        }
    }
    return "";
}