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:edu.vt.vbi.patric.portlets.CircosGenomeViewerPortlet.java

public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException {

    Map<String, Object> parameters = new LinkedHashMap<>();
    int fileCount = 0;

    try {//w  ww.  j a  v a  2 s .co m
        List<FileItem> items = new PortletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        for (FileItem item : items) {
            if (item.isFormField()) {
                parameters.put(item.getFieldName(), item.getString());
            } else {
                if (item.getFieldName().matches("file_(\\d+)$")) {
                    parameters.put("file_" + fileCount, item);
                    fileCount++;
                }
            }
        }
    } catch (FileUploadException e) {
        LOGGER.error(e.getMessage(), e);
    }

    LOGGER.debug(parameters.toString());

    // Generate Circo Image
    CircosData circosData = new CircosData(request);
    Circos circosConf = circosGenerator.createCircosImage(circosData, parameters);

    if (circosConf != null) {
        String baseUrl = "https://" + request.getServerName();
        String redirectUrl = baseUrl
                + "/portal/portal/patric/CircosGenomeViewer/CircosGenomeViewerWindow?action=b&cacheability=PAGE&imageId="
                + circosConf.getUuid() + "&trackList=" + StringUtils.join(circosConf.getTrackList(), ",");

        LOGGER.trace("redirect: {}", redirectUrl);
        response.sendRedirect(redirectUrl);
    }
}

From source file:Controller.ProsesRegis.java

private void processFormField(FileItem item) {
    if (item.getFieldName().equals("ids")) {
        IdStudent = item.getString();
    } else if (item.getFieldName().equals("idm")) {
        IdMajor = item.getString();/*from   w w w .ja  v a  2  s  . co  m*/
    } else if (item.getFieldName().equals("name")) {
        Fullname = item.getString();
    } else if (item.getFieldName().equals("gender")) {
        Gender = item.getString();
    } else if (item.getFieldName().equals("birth")) {
        Birth = item.getString();
    } else if (item.getFieldName().equals("school")) {
        School = item.getString();
    } else if (item.getFieldName().equals("major")) {
        Major = item.getString();
    } else if (item.getFieldName().equals("address")) {
        Address = item.getString();
    } else if (item.getFieldName().equals("phone")) {
        Phone = item.getString();
    } else if (item.getFieldName().equals("email")) {
        Email = item.getString();
    } else if (item.getFieldName().equals("gra-year")) {
        Grayear = item.getString();
    } else if (item.getFieldName().equals("photoubah")) {
        Photo = item.getString();
    }
}

From source file:br.com.sislivros.servlets.RecDadosCometGroup.java

protected void processRequest(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    resp.setContentType("text/html;charset=UTF-8");
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);
    String caminho;/* w w w . j a v  a  2  s .c  o  m*/
    if (isMultipart) {
        try {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = (List<FileItem>) upload.parseRequest(req);
            for (FileItem item : items) {
                if (item.isFormField()) {
                    req.setAttribute(item.getFieldName(), item.getString());
                    //                  resp.getWriter().println("No  campo file"+ this.getServletContext().getRealPath("/img"));
                    resp.getWriter().println("Name campo: " + item.getFieldName());
                    resp.getWriter().println("Value campo: " + item.getString());

                } else {
                    //caso seja um campo do tipo file

                    //                  resp.getWriter().println("Valor do Campo: ");
                    //                  resp.getWriter().println("Campo file");
                    //                  resp.getWriter().println("Name:"+item.getFieldName());
                    //                  resp.getWriter().println("nome arquivo: "+item.getName());
                    //                  resp.getWriter().println("Size:"+item.getSize());
                    //                  resp.getWriter().println("ContentType:"+item.getContentType());
                    if (item.getName() == "" || item.getName() == null) {
                        caminho = "";
                    } else {
                        caminho = "img" + File.separator + new Date().getTime() + "_" + item.getName();
                        resp.getWriter().println("Caminho: " + caminho);
                        //                          File uploadedFile = new File("C:\\TomCat\\apache-tomcat-8.0.21\\webapps\\sislivros\\" + caminho);
                        File uploadedFile = new File(
                                "E:\\Documentos\\NetBeansProjects\\sislivrosgit\\sisLivro\\build\\web\\"
                                        + caminho);
                        item.write(uploadedFile);
                    }

                    req.setAttribute("caminho", caminho);
                    //                        req.setAttribute("param", req.getParameter("comment-add"));
                    req.getRequestDispatcher("editarGrupo").forward(req, resp);
                }

            }

        } catch (Exception e) {
            resp.getWriter().println("ocorreu um problema ao fazer o upload: " + e.getMessage());
        }
    }
}

From source file:de.mpg.mpdl.service.rest.screenshot.service.HtmlScreenshotService.java

/**
 * Return the Field (param) with the given name as a {@link FileItem}
 * //from w  ww  . j  av a2 s  .co  m
 * @param items
 * @param name
 * @return
 */
private String getFieldValue(List<FileItem> items, String name) {
    for (FileItem item : items) {
        if (item.isFormField() && name.equals(item.getFieldName())) {
            return item.getString();
        }
    }
    return null;
}

From source file:edu.caltech.ipac.firefly.server.servlets.WebPlotServlet.java

protected void processRequest(HttpServletRequest req, HttpServletResponse res) throws Exception {

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

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    // Parse the request
    List /* FileItem */ items = upload.parseRequest(req);

    Map<String, String> params = new HashMap<String, String>(10);

    // 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 = item.getString();
            params.put(name, value);/*from  ww w .  j a v a 2s .c o  m*/
        } else {
            String fieldName = item.getFieldName();
            try {
                File uf = new File(ServerContext.getTempWorkDir(), System.currentTimeMillis() + ".upload");
                item.write(uf);
                params.put(fieldName, uf.getPath());

            } catch (Exception e) {
                sendReturnMsg(res, 500, e.getMessage(), null);
                return;
            }
        }
    }

    //        String result= ServerCommandAccess.doCommand(params);

    //        sendReturnMsg(res, 200, "results", result);

    // test code..
    //        if (doTest) {
    //            MultiPartPostBuilder builder = new MultiPartPostBuilder(
    //                                    "http://localhost:8080/applications/Spitzer/SHA/servlet/Firefly_MultiPartHandler");
    //            builder.addParam("dummy1", "boo1");
    //            builder.addParam("dummy2", "boo2");
    //            builder.addParam("dummy3", "boo3");
    //            for(UploadFileInfo fi : data.getFiles()) {
    //                builder.addFile(fi.getPname(), fi.getFile());
    //            }
    //            StringWriter sw = new StringWriter();
    //            MultiPartPostBuilder.MultiPartRespnse pres = builder.post(sw);
    //            LOG.briefDebug("uploaded status: " + pres.getStatusMsg());
    //            LOG.debug("uploaded response: " + sw.toString());
    //        }
}

From source file:com.threecrickets.prudence.internal.lazy.LazyInitializationFile.java

@Override
protected void initialize() {
    if ((request.getMethod().equals(Method.POST) || request.getMethod().equals(Method.PUT))
            && request.isEntityAvailable()
            && request.getEntity().getMediaType().includes(MediaType.MULTIPART_FORM_DATA)) {
        try {//ww w  .  j a v a2  s.c om
            for (FileItem fileItem : fileUpload.parseRequest(request)) {
                if (fileItem.isFormField())
                    formFields.put(fileItem.getFieldName(), fileItem.getString());
                else
                    map.put(fileItem.getFieldName(), Collections.unmodifiableMap(createFileItemMap(fileItem)));
            }
        } catch (FileUploadException x) {
            x.printStackTrace();
        }
    }
}

From source file:fr.gael.dhus.server.http.webapp.api.controller.UploadController.java

@PreAuthorize("hasRole('ROLE_UPLOAD')")
@RequestMapping(value = "/upload", method = { RequestMethod.POST })
public void upload(Principal principal, HttpServletRequest req, HttpServletResponse res) throws IOException {
    // process only multipart requests
    if (ServletFileUpload.isMultipartContent(req)) {
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Parse the request
        try {/*from w  w  w .j a va 2s.  com*/
            ArrayList<String> collectionIds = new ArrayList<>();
            FileItem product = null;

            List<FileItem> items = upload.parseRequest(req);
            for (FileItem item : items) {
                if (COLLECTIONSKEY.equals(item.getFieldName())) {
                    if (item.getString() != null && !item.getString().isEmpty()) {
                        for (String cid : item.getString().split(",")) {
                            collectionIds.add(cid);
                        }
                    }
                } else if (PRODUCTKEY.equals(item.getFieldName())) {
                    product = item;
                }
            }
            if (product == null) {
                res.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Your request is missing a product file to upload.");
                return;
            }
            productUploadService.upload(product, collectionIds);
            res.setStatus(HttpServletResponse.SC_CREATED);
            res.getWriter().print("The file was created successfully.");
            res.flushBuffer();
        } catch (FileUploadException e) {
            LOGGER.error("An error occurred while parsing request.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while parsing request : " + e.getMessage());
        } catch (UserNotExistingException e) {
            LOGGER.error("You need to be connected to upload a product.", e);
            res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "You need to be connected to upload a product.");
        } catch (UploadingException e) {
            LOGGER.error("An error occurred while uploading the product.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while uploading the product : " + e.getMessage());
        } catch (RootNotModifiableException e) {
            LOGGER.error("An error occurred while uploading the product.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while uploading the product : " + e.getMessage());
        } catch (ProductNotAddedException e) {
            LOGGER.error("Your product can not be read by the system.", e);
            res.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Your product can not be read by the system.");
        }
    } else {
        res.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                "Request contents type is not supported by the servlet.");
    }
}

From source file:gr.forth.ics.isl.x3mlEditor.upload.MultipartUploadParser.java

private void parseFormFields(List<FileItem> items) {
    for (FileItem item : items) {
        if (item.isFormField()) {
            String key = item.getFieldName();
            String value = item.getString();
            if (StringUtils.isNotBlank(key)) {
                params.put(key.toLowerCase(), StringUtils.defaultString(value));
            }//from w  w  w .j  a  v  a 2s  .  c o  m
        } else {
            files.add(item);
        }
    }
}

From source file:fr.gael.dhus.api.UploadController.java

@SuppressWarnings("unchecked")
@PreAuthorize("hasRole('ROLE_UPLOAD')")
@RequestMapping(value = "/upload", method = { RequestMethod.POST })
public void upload(Principal principal, HttpServletRequest req, HttpServletResponse res) throws IOException {
    // process only multipart requests
    if (ServletFileUpload.isMultipartContent(req)) {
        User user = (User) ((UsernamePasswordAuthenticationToken) principal).getPrincipal();
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Parse the request
        try {//from ww w  .ja  v a 2 s  . c o  m
            ArrayList<Long> collectionIds = new ArrayList<>();
            FileItem product = null;

            List<FileItem> items = upload.parseRequest(req);
            for (FileItem item : items) {
                if (COLLECTIONSKEY.equals(item.getFieldName())) {
                    if (item.getString() != null && !item.getString().isEmpty()) {
                        for (String cid : item.getString().split(",")) {
                            collectionIds.add(new Long(cid));
                        }
                    }
                } else if (PRODUCTKEY.equals(item.getFieldName())) {
                    product = item;
                }
            }
            if (product == null) {
                res.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Your request is missing a product file to upload.");
                return;
            }
            productUploadService.upload(user.getId(), product, collectionIds);
            res.setStatus(HttpServletResponse.SC_CREATED);
            res.getWriter().print("The file was created successfully.");
            res.flushBuffer();
        } catch (FileUploadException e) {
            logger.error("An error occurred while parsing request.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while parsing request : " + e.getMessage());
        } catch (UserNotExistingException e) {
            logger.error("You need to be connected to upload a product.", e);
            res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "You need to be connected to upload a product.");
        } catch (UploadingException e) {
            logger.error("An error occurred while uploading the product.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while uploading the product : " + e.getMessage());
        } catch (RootNotModifiableException e) {
            logger.error("An error occurred while uploading the product.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while uploading the product : " + e.getMessage());
        } catch (ProductNotAddedException e) {
            logger.error("Your product can not be read by the system.", e);
            res.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Your product can not be read by the system.");
        }
    } else {
        res.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                "Request contents type is not supported by the servlet.");
    }
}

From source file:controller.addGame.java

private void processFormField(FileItem item) {
    if (item.getFieldName().equals("AppName")) {
        AppName = item.getString();
    } else if (item.getFieldName().equals("RecRam")) {
        String a = item.getString();
        RecRam = Integer.parseInt(a);
    } else if (item.getFieldName().equals("Code")) {
        Code = item.getString();/*from   w  w w  .  ja va2 s  .co  m*/
    } else if (item.getFieldName().equals("MinCpu")) {
        MinCpu = item.getString();
    } else if (item.getFieldName().equals("RecCpu")) {
        RecCpu = item.getString();
    } else if (item.getFieldName().equals("MinGpu")) {
        MinGpu = item.getString();
    } else if (item.getFieldName().equals("RecGpu")) {
        RecGpu = item.getString();
    } else if (item.getFieldName().equals("MinCpuLvl")) {
        String a = item.getString();
        MinCpuLvl = Integer.parseInt(a);
    } else if (item.getFieldName().equals("RecCpuLvl")) {
        String a = item.getString();
        RecCpuLvl = Integer.parseInt(a);
    } else if (item.getFieldName().equals("MinGpuLvl")) {
        String a = item.getString();
        MinGpuLvl = Integer.parseInt(a);
    } else if (item.getFieldName().equals("RecGpuLvl")) {
        String a = item.getString();
        RecGpuLvl = Integer.parseInt(a);
    } else if (item.getFieldName().equals("MinRam")) {
        String a = item.getString();
        MinRam = Integer.parseInt(a);
    }
}