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:controller.AddNewEC.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  w w  w.j av  a 2s.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 {
    response.setContentType("text/html;charset=UTF-8");
    ExtenuatingCircumstance ec = new ExtenuatingCircumstance();
    if (ServletFileUpload.isMultipartContent(request)) {
        try {
            int year = 0;
            String fname = StringUtils.EMPTY;
            String title = StringUtils.EMPTY;
            String desciption = StringUtils.EMPTY;
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
            ArrayList<FileItem> files = new ArrayList<>();
            for (FileItem item : multiparts) {
                if (item.isFormField()) {
                    if (item.getFieldName().equals("year")) {
                        year = Integer.parseInt(item.getString());
                    }
                    if (item.getFieldName().equals("title")) {
                        title = item.getString();
                    }
                    if (item.getFieldName().equals("description")) {
                        desciption = item.getString();
                    }

                } else {
                    if (StringUtils.isNotEmpty(item.getName())) {
                        files.add(item);
                    }
                }
            }

            HttpSession session = request.getSession(false);
            Account studentAccount = (Account) session.getAttribute("account");
            LocalDateTime now = WsadUtils.GetCurrentDatetime();

            // insert EC
            ec.setAcademicYear(year);
            ec.setTitle(title);
            ec.setDescription(desciption);
            ec.setProcess_status("submitted");
            ec.setSubmitted_date(now.toString());
            ec.setAccount(studentAccount.getId());

            ExtenuatingCircumstance insertedEC = new ExtenuatingCircumstanceDAO().insertEC(ec);

            //insert assigned coordinator
            Account coordinator = new AccountDAO().getCoordinator(studentAccount.getFaculty());
            insertAssignedCoordinator(coordinator, insertedEC);

            //insert evidence
            insertedEvidence(files, now, insertedEC, studentAccount);

            String mailContent = WsadUtils.buildMailContentForNewEC(insertedEC);
            SendMail.sendMail(coordinator.getEmail(), "New EC", mailContent);

        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        request.setAttribute("message", "Sorry this Servlet only handles file upload request");
    }

    request.setAttribute("resultMsg", "inserted");
    request.getRequestDispatcher("AddNewECResult.jsp").forward(request, response);
}

From source file:com.arcadian.loginservlet.StudentAssignmentServlet.java

/**
 * Handles the HTTP/*from  w w  w . j  av  a 2  s.co  m*/
 * <code>POST</code> method.
 *
 * @param request servlet request
 * @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 {

    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new ServletException("Content type is not multipart/form-data");
    }
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    try {
        List<FileItem> fileItemsList = uploader.parseRequest(request);
        Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();

        String assignmentid = "";
        String filename = "";
        while (fileItemsIterator.hasNext()) {

            FileItem fileItem = fileItemsIterator.next();
            System.out.println(fileItem);
            if (fileItem.isFormField()) {

                String name = fileItem.getFieldName();
                String value = fileItem.getString();

                if (name.equalsIgnoreCase("assignmentid")) {
                    assignmentid = value;
                }
                System.out.println("Assignment id==" + assignmentid);
            }

            if (fileItem.getName() != null) {

                File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator
                        + fileItem.getName());
                System.out.println("Absolute Path at server=" + file.getAbsolutePath());
                fileItem.write(file);
                filename = fileItem.getName();
            }

        }
        assignmentFoldetService = new AssignmentFolderService();
        assignmentFoldetService.updateAssignmentFolder(username, assignmentid, filename);

    } catch (FileUploadException e) {
        System.out.println("Exception in file upload" + e);
    } catch (Exception ex) {
        Logger.getLogger(CourseContentServlet.class.getName()).log(Level.SEVERE, null, ex);
    }

    processRequest(request, response);
}

From source file:massbank.FileUpload.java

/**
 * NGXgp??[^?/*from www.  jav  a 2  s .  c om*/
 * multipart/form-data?NGXg?
 * s??nullp
 * @return ?NGXg?MAP<L?[, l>
 */
@SuppressWarnings("unchecked")
public HashMap<String, String[]> getRequestParam() {

    if (fileItemList == null) {
        try {
            fileItemList = (List<FileItem>) parseRequest(req);
        } catch (FileUploadException e) {
            e.printStackTrace();
            return null;
        }
    }

    HashMap<String, String[]> reqParamMap = new HashMap<String, String[]>();
    for (FileItem fItem : fileItemList) {

        // ?tB?[h???iNGXgp??[^lz???j
        if (fItem.isFormField()) {
            String key = fItem.getFieldName();
            String val = fItem.getString();
            if (key != null && !key.equals("")) {
                reqParamMap.put(key, new String[] { val });
            }
        }
    }
    return reqParamMap;
}

From source file:MyPack.AddAuctionItems.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  ww  w  .j ava 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 {
    config = getServletConfig();
    System.out.println("Inside insert code");
    try {

        session = request.getSession();
        int regid = (Integer) session.getAttribute("regid");
        String itemname = "";
        int itemprice = 0;
        String date = "";
        String time = "";
        int catid = 0;
        String itempic = "";

        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 ex) {
                Logger.getLogger(AddAuctionItems.class.getName()).log(Level.SEVERE, null, ex);
            }
            Iterator itr = items.iterator();
            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();
                if (item.isFormField()) {
                    String name = item.getFieldName();
                    String value = item.getString();
                    if (name.equals("itemname")) {
                        itemname = value;
                        //                      count1=1;
                        System.out.println("name = " + itemname);
                    }
                    if (name.equals("itemprice")) {
                        itemprice = Integer.parseInt(value);
                        //                         count2=2;
                        System.out.println("price = " + itemprice);
                    }
                    if (name.equals("itemdate")) {
                        date = value;
                        //                         count5=5;
                        System.out.println("date = " + date);
                    }
                    if (name.equals("itemtime")) {
                        time = value;
                        // count3=3;
                        System.out.println("time = " + time);
                    }

                    if (name.equals("selectedRecord")) {
                        //                     count4=4;
                        catid = Integer.parseInt(value);
                        System.out.println("emp_emailid = " + catid);
                    }

                } else {
                    try {

                        itempic = item.getName();
                        System.out.println("itemName============" + itempic);
                        File savedFile = new File(
                                config.getServletContext().getRealPath("/") + "../../web/upimage\\" + itempic);
                        //                            System.out.println(config.getServletContext().getRealPath("/") + "upimage\\" + itempic);
                        item.write(savedFile);

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

        PrintWriter out = response.getWriter();
        DBConnection Db = new DBConnection();
        String sql = "insert into tb_auction_items values(null,'" + itemname + "','" + itemprice + "','" + date
                + "','" + time + "','0','" + catid + "','" + regid + "','" + itempic + "')";
        System.out.println(sql);
        int row = Db.UpdateQuery(sql);
        if (row > 0) {
            out.print("<script>alert('Successulyy added');</script>");
            response.sendRedirect("viewitems");
            // request.getRequestDispatcher("viewitems").include(request, response);

        } else {
            request.getRequestDispatcher("AddAuctionItemss.jsp").forward(request, response);
            out.print("<script>alert('Failed to Update');</script>");
        }
        Db.Close();
    } catch (Exception ex) {
        Logger.getLogger(AddAuctionItems.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.meetme.plugins.jira.gerrit.adminui.AdminServlet.java

private void setAllFields(final List<FileItem> items) {
    for (FileItem item : items) {
        final String fieldName = item.getFieldName();

        if (fieldName.equals(GerritConfiguration.FIELD_HTTP_BASE_URL)) {
            configurationManager.setHttpBaseUrl(item.getString());
        } else if (fieldName.equals(GerritConfiguration.FIELD_HTTP_USERNAME)) {
            configurationManager.setHttpUsername(item.getString());
        } else if (fieldName.equals(GerritConfiguration.FIELD_HTTP_PASSWORD)) {
            configurationManager.setHttpPassword(item.getString());
        } else if (fieldName.equals(GerritConfiguration.FIELD_SSH_HOSTNAME)) {
            configurationManager.setSshHostname(item.getString());
        } else if (fieldName.equals(GerritConfiguration.FIELD_SSH_USERNAME)) {
            configurationManager.setSshUsername(item.getString());
        } else if (fieldName.equals(GerritConfiguration.FIELD_SSH_PORT)) {
            configurationManager.setSshPort(Integer.parseInt(item.getString()));
        } else if (fieldName.equals(GerritConfiguration.FIELD_QUERY_ISSUE)) {
            configurationManager.setIssueSearchQuery(item.getString());
        } else if (fieldName.equals(GerritConfiguration.FIELD_QUERY_PROJECT)) {
            configurationManager.setProjectSearchQuery(item.getString());
        }//from  ww  w  .j  a va  2s. com
    }
}

From source file:ca.qc.cegepoutaouais.tge.pige.server.UserImportService.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    hasError = Boolean.FALSE;//from w w  w  .j  a  va  2s .  co m
    writer = resp.getWriter();

    logger.info("Rception de la requte HTTP pour l'imporation d'usagers.");

    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(SIZE_THRESHOLD);

    ServletFileUpload uploadHandler = new ServletFileUpload(factory);
    try {
        List<FileItem> items = uploadHandler.parseRequest(req);
        if (items.size() == 0) {
            logger.error("Le message ne contient pas de fichier "
                    + "d'importation. Le processus ne pourra donc pas " + "continuer.");
            writer.println("Erreur: Aucun fichier prsent dans le message");
            return;
        }

        Charset cs = null;
        for (FileItem item : items) {
            if (item.getFieldName().equalsIgnoreCase("importFileEncoding-hidden")) {
                String encoding = item.getString();
                if (encoding == null || encoding.isEmpty()) {
                    logger.error("Le message ne contient pas l'encodage utilis "
                            + "dans le fichier d'importation. Le processus ne pourra " + "donc pas continuer.");
                    writer.println("Erreur: Aucun encodage trouv dans les " + "paramtres du message.");
                    return;
                }
                cs = Charset.forName(encoding);
                if (cs == null) {
                    logger.error("L'encodage spcifi n'existe pas (" + encoding + "). "
                            + "Le processus ne pourra donc pas continuer.");
                    writer.println("Erreur: Aucun encodage trouv portant le " + "nom '" + encoding + "'.");
                    return;
                }
            }
        }

        for (FileItem item : items) {
            if (item.getFieldName().equalsIgnoreCase("usersImportFile")) {
                logger.info("Extraction du fichier d'importation  partir " + "du message.");
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(new ByteArrayInputStream(item.get()), cs));
                doUsersImport(reader, req);
                break;
            }
        }

        if (!hasError) {
            logger.info("L'importation des usagers s'est termine avec succs.");
            writer.println("Importation russie!");
        } else {
            logger.info("L'importation des usagers s'est termine avec des erreurs.");
            writer.println("L'importation s'est termine avec des erreurs.");
        }

    } catch (FileUploadException fuex) {
        fuex.printStackTrace();
        logger.error(fuex);
    } catch (Exception ex) {
        ex.printStackTrace();
        logger.error(ex);
    }

}

From source file:mercury.Controller.java

public void putAllRequestParametersInAttributes(HttpServletRequest request) {
    ArrayList fileBeanList = new ArrayList();
    HashMap<String, String> ht = new HashMap<String, String>();

    String fieldName = null;/*from  w  ww  . j a  v a2s . co  m*/
    String fieldValue = null;
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        java.util.List items = null;
        try {
            items = upload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        Iterator iter = items.iterator();

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

            if (item.isFormField()) {
                fieldName = item.getFieldName();
                fieldValue = item.getString();
                ht.put(fieldName, fieldValue);
            } else if (!item.isFormField()) {
                UploadedFileBean bean = new UploadedFileBean();
                bean.setFileItem(item);
                bean.setContentType(item.getContentType());
                bean.setFileName(item.getName());
                try {
                    bean.setInputStream(item.getInputStream());
                } catch (Exception e) {
                    System.out.println("=== Erro: " + e);
                }
                bean.setIsInMemory(item.isInMemory());
                bean.setSize(item.getSize());
                fileBeanList.add(bean);
                request.getSession().setAttribute("UPLOADED_FILE", bean);
            }
        }
    } else if (!isMultipart) {
        Enumeration<String> en = request.getParameterNames();

        String name = null;
        String value = null;
        while (en.hasMoreElements()) {
            name = en.nextElement();
            value = request.getParameter(name);
            ht.put(name, value);
        }
    }

    request.setAttribute("REQUEST_PARAMETERS", ht);
}

From source file:cn.itcast.fredck.FCKeditor.uploader.SimpleUploaderServlet.java

/**
 * Manage the Upload requests.<br>
 *
 * The servlet accepts commands sent in the following format:<br>
 * simpleUploader?Type=ResourceType<br><br>
 * It store the file (renaming it in case a file with the same name exists) and then return an HTML file
 * with a javascript command in it./*from ww w. ja  va 2 s. c o m*/
 *
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (debug)
        System.out.println("--- BEGIN DOPOST ---");

    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String typeStr = request.getParameter("Type");

    String currentPath = baseDir + typeStr;
    String currentDirPath = getServletContext().getRealPath(currentPath);
    currentPath = request.getContextPath() + currentPath;

    if (debug)
        System.out.println(currentDirPath);

    String retVal = "0";
    String newName = "";
    String fileUrl = "";
    String errorMessage = "";

    if (enabled) {
        DiskFileUpload upload = new DiskFileUpload();
        try {
            List items = upload.parseRequest(request);

            Map fields = new HashMap();

            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField())
                    fields.put(item.getFieldName(), item.getString());
                else
                    fields.put(item.getFieldName(), item);
            }
            FileItem uplFile = (FileItem) fields.get("NewFile");
            String fileNameLong = uplFile.getName();
            fileNameLong = fileNameLong.replace('\\', '/');
            String[] pathParts = fileNameLong.split("/");
            String fileName = pathParts[pathParts.length - 1];

            String nameWithoutExt = getNameWithoutExtension(fileName);
            String ext = getExtension(fileName);
            File pathToSave = new File(currentDirPath, fileName);
            fileUrl = currentPath + "/" + fileName;
            if (extIsAllowed(typeStr, ext)) {
                int counter = 1;
                while (pathToSave.exists()) {
                    newName = nameWithoutExt + "(" + counter + ")" + "." + ext;
                    fileUrl = currentPath + "/" + newName;
                    retVal = "201";
                    pathToSave = new File(currentDirPath, newName);
                    counter++;
                }
                uplFile.write(pathToSave);
            } else {
                retVal = "202";
                errorMessage = "";
                if (debug)
                    System.out.println("Invalid file type: " + ext);
            }
        } catch (Exception ex) {
            if (debug)
                ex.printStackTrace();
            retVal = "203";
        }
    } else {
        retVal = "1";
        errorMessage = "This file uploader is disabled. Please check the WEB-INF/web.xml file";
    }

    out.println("<script type=\"text/javascript\">");
    out.println("window.parent.OnUploadCompleted(" + retVal + ",'" + fileUrl + "','" + newName + "','"
            + errorMessage + "');");
    out.println("</script>");
    out.flush();
    out.close();

    if (debug)
        System.out.println("--- END DOPOST ---");

}

From source file:com.xclinical.mdr.server.DocumentServlet.java

@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    try {//w w  w . ja v  a  2 s . c om
        if (ServletFileUpload.isMultipartContent(req)) {
            log.debug("detected multipart content");

            final FileInfo info = new FileInfo();

            ServletFileUpload fileUpload = new ServletFileUpload(new DiskFileItemFactory());

            @SuppressWarnings("unchecked")
            List<FileItem> items = fileUpload.parseRequest(req);

            String session = null;

            for (Iterator<FileItem> i = items.iterator(); i.hasNext();) {
                log.debug("detected form field");

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

                if (item.isFormField()) {
                    String fieldName = item.getFieldName();
                    String fieldValue = item.getString();

                    if (fieldName != null) {
                        log.debug("{0}={1}", fieldName, fieldValue);
                    } else {
                        log.severe("fieldName may not be null");
                    }

                    if ("session".equals(fieldName)) {
                        session = fieldValue;
                    }
                } else {
                    log.debug("detected content");

                    info.contentName = item.getName();
                    info.contentName = new File(info.contentName).getName();
                    info.contentType = item.getContentType();
                    info.content = item.get();

                    log.debug("{0} bytes", info.content.length);
                }
            }

            if (info.content == null)
                throw new IllegalArgumentException("there is no content");
            if (info.contentType == null)
                throw new IllegalArgumentException("There is no content type");
            if (info.contentName == null)
                throw new IllegalArgumentException("There is no content name");

            Session.runInSession(session, new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    Document document = Document.create(info.contentName, info.contentType, info.content);

                    log.info("Created document " + document.getId());

                    ReferenceDocument referenceDocument = saveFile(req, document);

                    JsonCommandServlet.writeResponse(resp, FlatJsonExporter.of(referenceDocument));
                    return null;
                }
            });
        } else {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }

    } catch (FileUploadException e) {
        log.severe(e);
        throw new ServletException(e);
    } catch (Exception e) {
        log.severe(e);
        throw new ServletException(e);
    }
}

From source file:com.carolinarollergirls.scoreboard.jetty.MediaServlet.java

protected void upload(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//from   w  w  w.j  a  va 2 s  .  co  m
        if (!ServletFileUpload.isMultipartContent(request)) {
            response.sendError(response.SC_BAD_REQUEST);
            return;
        }

        String media = null, type = null;
        FileItemFactory fiF = new DiskFileItemFactory();
        ServletFileUpload sfU = new ServletFileUpload(fiF);
        List<FileItem> fileItems = new LinkedList<FileItem>();
        Iterator i = sfU.parseRequest(request).iterator();

        while (i.hasNext()) {
            FileItem item = (FileItem) i.next();
            if (item.isFormField()) {
                if (item.getFieldName().equals("media"))
                    media = item.getString();
                else if (item.getFieldName().equals("type"))
                    type = item.getString();
            } else if (item.getName().matches(zipExtRegex)) {
                processZipFileItem(fiF, item, fileItems);
            } else if (uploadFileNameFilter.accept(null, item.getName())) {
                fileItems.add(item);
            }
        }

        if (fileItems.size() == 0) {
            setTextResponse(response, response.SC_BAD_REQUEST, "No files provided to upload");
            return;
        }

        processFileItemList(fileItems, media, type);

        int len = fileItems.size();
        setTextResponse(response, response.SC_OK,
                "Successfully uploaded " + len + " file" + (len > 1 ? "s" : ""));
    } catch (FileNotFoundException fnfE) {
        setTextResponse(response, response.SC_NOT_FOUND, fnfE.getMessage());
    } catch (IllegalArgumentException iaE) {
        setTextResponse(response, response.SC_BAD_REQUEST, iaE.getMessage());
    } catch (FileUploadException fuE) {
        setTextResponse(response, response.SC_INTERNAL_SERVER_ERROR, fuE.getMessage());
    }
}