Example usage for org.apache.commons.fileupload.disk DiskFileItem getFieldName

List of usage examples for org.apache.commons.fileupload.disk DiskFileItem getFieldName

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.disk DiskFileItem getFieldName.

Prototype

public String getFieldName() 

Source Link

Document

Returns the name of the field in the multipart form corresponding to this file item.

Usage

From source file:fr.ippon.wip.http.request.MultipartRequestBuilder.java

public HttpRequestBase buildHttpRequest() throws URISyntaxException {
    MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    try {//from   w  w w.java 2s  .  c  o  m
        for (DiskFileItem fileItem : files) {
            if (fileItem.isFormField())
                multipartEntity.addPart(fileItem.getFieldName(), new StringBody(new String(fileItem.get())));
            else {
                //               FileBody fileBody = new FileBody(fileItem.getStoreLocation(), fileItem.getName(), fileItem.getContentType(), fileItem.getCharSet());
                InputStreamBody fileBody = new InputStreamKnownSizeBody(fileItem.getInputStream(),
                        fileItem.get().length, fileItem.getContentType(), fileItem.getName());
                multipartEntity.addPart(fileItem.getFieldName(), fileBody);
            }
        }

        // some request may have additional parameters in a query string
        if (parameterMap != null)
            for (Entry<String, String> entry : parameterMap.entries())
                multipartEntity.addPart(entry.getKey(), new StringBody(entry.getValue()));

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

    HttpPost postRequest = new HttpPost(requestedURL);
    postRequest.setEntity(multipartEntity);
    return postRequest;
}

From source file:cServ.AltaDoc.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w ww  .j a  va  2 s . c om
 *
 * @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");
    try (PrintWriter out = response.getWriter()) {
        System.out.println("hit altadoc");

        //begin database operation
        String nomArch = "";
        String nombre = "";
        String contra = "";
        int id = 0;
        System.out.println(request.getParameter("idprofe"));
        String displayString = "Contrasea incorrecta";
        String divColor = "danger";
        String rdrUrl = "<meta http-equiv=\"refresh\" content=\"2;url=pages/profesor/adminDocs.jsp\" >";

        //start file up
        FileItemFactory factory = new DiskFileItemFactory();

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

        // Parse the request
        List items = null;
        try {
            items = upload.parseRequest(request);
        } catch (Exception e) {
            e.printStackTrace();
        }

        for (Iterator it = items.iterator(); it.hasNext();) {
            DiskFileItem diskFileItem = (DiskFileItem) it.next();
            if (diskFileItem.isFormField()) {
                String fieldname = diskFileItem.getFieldName();
                String fieldvalue = diskFileItem.getString();
                System.out.println("fn: " + fieldname + " fv " + fieldvalue);
                if (fieldname.equals("nombre")) {
                    nombre = fieldvalue;
                } else if (fieldname.equals("contra")) {
                    contra = fieldvalue;
                } else if (fieldname.equals("idprofe")) {
                    id = Integer.parseInt(fieldvalue);
                }

            } else {

                //start getpath
                String relativeWebPath = "/../../web/pages/profesor/adminDocsPanels/docDump/";
                System.out.println("relative thing " + getServletContext().getRealPath(relativeWebPath));
                System.out.println(relativeWebPath);
                String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
                System.out.println("complete path " + absoluteDiskPath + "\\" + nomArch);
                absoluteDiskPath += "\\" + nomArch;
                //end getpath

                byte[] fileBytes = diskFileItem.get();
                nomArch = diskFileItem.getName();
                File file = new File(absoluteDiskPath + diskFileItem.getName());
                FileOutputStream fileOutputStream = new FileOutputStream(file);
                fileOutputStream.write(fileBytes);
                fileOutputStream.flush();
            }
        }

        //end file up
        //start db insertion
        Validator valid = new Validator();
        valid.ValidatePDF(nomArch);
        if (valid.isValid() == true) {
            String adString = altaDoc(id, nomArch);
            if (adString.equals("operacion realizada")) {
                displayString = "Documento dado de alta";
                divColor = "success";
                rdrUrl = "<meta http-equiv=\"refresh\" content=\"2;url=pages/profesor/adminDocs.jsp\" >";
            }
        } else {
            displayString = "Archivo no vlido";
            divColor = "danger";
            rdrUrl = "<meta http-equiv=\"refresh\" content=\"2;url=pages/profesor/adminDocs.jsp\" >";
        }
        //end db insertion

        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<link rel=\"stylesheet\" href=\"css/style.css\">");
        out.println("<title>Servlet AltaGrupo</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<div class=\"container\">\n" + "            <div class=\"row\">\n"
                + "                <br><br>\n" + "                <div class=\"panel panel-" + divColor
                + "\">\n" + "                    <div class=\"panel-heading\">\n"
                + "                        <h3 class=\"panel-title\">Espera</h3>\n"
                + "                    </div>\n" + "                    <div class=\"panel-body\">\n"
                + "                        " + displayString + " \n" + "                    </div>\n"
                + "                </div>\n" + "            </div>\n" + "        </div>");
        out.println(rdrUrl);
        out.println("</body>");
        out.println("</html>");
        //end database operation
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.globalsight.everest.webapp.pagehandler.administration.customer.FileSystemViewHandler.java

private Vector uploadTmpAttachmentFile(HttpServletRequest request, HttpSession session) {
    String tmpFoler = request.getParameter("folder");
    String uploadPath = AmbFileStoragePathUtils.getFileStorageDirPath() + File.separator + "GlobalSight"
            + File.separator + "CommentReference" + File.separator + "tmp" + File.separator + tmpFoler;
    try {/*from w ww.j  av a 2s  .co m*/
        boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
        if (isMultiPart) {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(1024000);
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);

            for (int i = 0; i < items.size(); i++) {
                DiskFileItem item = (DiskFileItem) items.get(i);
                if (!item.isFormField()) {
                    String fileName = item.getFieldName();
                    String filePath = uploadPath + File.separator + fileName;
                    File f = new File(filePath);
                    f.getParentFile().mkdirs();
                    item.write(f);
                }
            }
        }
    } catch (Exception e) {
        throw new EnvoyServletException(e);
    }
    return new Vector();
}

From source file:com.globalsight.everest.webapp.pagehandler.administration.customer.FileSystemViewHandler.java

private Vector uploadTmpFiles(HttpServletRequest request, HttpSession session) {
    String tmpFoler = request.getParameter("folder");
    String uploadPath = AmbFileStoragePathUtils.getCxeDocDir() + File.separator
            + CreateJobsMainHandler.TMP_FOLDER_NAME + File.separator + tmpFoler;
    try {//from  w  ww  .  ja  v a  2  s  .  c  om
        boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
        if (isMultiPart) {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(1024000);
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);

            for (int i = 0; i < items.size(); i++) {
                DiskFileItem item = (DiskFileItem) items.get(i);
                if (!item.isFormField()) {
                    String filePath = item.getFieldName();
                    if (filePath.contains(":")) {
                        filePath = filePath.substring(filePath.indexOf(":") + 1);
                    }
                    String originalFilePath = filePath.replace("\\", File.separator).replace("/",
                            File.separator);
                    String fileName = uploadPath + File.separator + originalFilePath;
                    File f = new File(fileName);
                    f.getParentFile().mkdirs();
                    item.write(f);

                    String extension = FileUtils.getFileExtension(f);
                    if (extension != null && extension.equalsIgnoreCase("zip")) {
                        unzipFile(f);
                        f.delete();
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new EnvoyServletException(e);
    }
    return new Vector();
}

From source file:com.novartis.opensource.yada.YADARequest.java

/**
 * Sets the upload items which will then be dervied from the
 * YADARequest by the preprocessor plugin
 * /*  ww  w.  ja  v a 2 s . c  o  m*/
 * @param uploadItems list of form field name/value pairs and upload content
 * @throws YADARequestException when a method invocation problem occurs while setting parameter values
 */
public void setUploadItems(List<FileItem> uploadItems) throws YADARequestException {
    this.uploadItems = uploadItems;
    Iterator<FileItem> iter = uploadItems.iterator();
    while (iter.hasNext()) {
        DiskFileItem fi = (DiskFileItem) iter.next();
        l.debug(fi);
        // set parameters from form fields
        if (fi.isFormField()) {
            String field = fi.getFieldName();
            String value = fi.getString();
            l.debug("field is [" + field + "], value is [" + value + "]");
            invokeSetter(field, new String[] { value });
            addToMap(field, new String[] { value });
        } else {
            File f;
            String fPath;
            String fName;
            try {
                // execute plugin, as we are not calling a WS
                f = fi.getStoreLocation(); // tmp dir
                fPath = f.getAbsolutePath(); // uploaded file
                fName = fi.getName(); // original file name
            } finally {
                f = null;
            }
            addArg(fPath);
            addArg(fName);
        }
    }
    l.debug(getFormattedDebugString("uploadItems", uploadItems.toString()));
}

From source file:org.apache.axis2.builder.MultipartFormDataBuilder.java

private MultipleEntryHashMap getParameterMap(RequestContext request, String charSetEncoding)
        throws FileUploadException {

    MultipleEntryHashMap parameterMap = new MultipleEntryHashMap();

    List items = parseRequest(request);
    Iterator iter = items.iterator();
    while (iter.hasNext()) {
        DiskFileItem diskFileItem = (DiskFileItem) iter.next();

        boolean isFormField = diskFileItem.isFormField();

        Object value;/*from ww  w  . j  a v  a2  s .com*/
        try {
            if (isFormField) {
                value = getTextParameter(diskFileItem, charSetEncoding);
            } else {
                value = getFileParameter(diskFileItem);
            }
        } catch (Exception ex) {
            throw new FileUploadException(ex.getMessage());
        }
        parameterMap.put(diskFileItem.getFieldName(), value);
    }

    return parameterMap;
}

From source file:org.datacleaner.monitor.server.media.FileUploadServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    clearSession(req);//from   w  w w  .  ja  va 2s  .c o m

    File tempFolder = FileHelper.getTempDir();
    try {
        File subDirectory = new File(tempFolder, ".datacleaner_upload");
        if (subDirectory.mkdirs()) {
            tempFolder = subDirectory;
        }
    } catch (Exception e) {
        logger.warn("Could not create subdirectory in temp folder", e);
    }

    final FileItemFactory fileItemFactory = new DiskFileItemFactory(0, tempFolder);
    final ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
    servletFileUpload.setFileSizeMax(FILE_SIZE_MAX);
    servletFileUpload.setSizeMax(REQUEST_SIZE_MAX);

    final List<Object> resultFileElements = new ArrayList<Object>();
    final HttpSession session = req.getSession();

    try {
        int index = 0;
        @SuppressWarnings("unchecked")
        final List<DiskFileItem> items = servletFileUpload.parseRequest(req);
        for (DiskFileItem item : items) {
            if (item.isFormField()) {
                logger.warn("Ignoring form field in request: {}", item);
            } else {
                final String sessionKey = "file_upload_" + index;
                final File file = item.getStoreLocation();

                String filename = toFilename(item.getName());
                logger.info("File '{}' uploaded to temporary location: {}", filename, file);

                session.setAttribute(sessionKey, file);

                final Map<String, String> resultItem = new LinkedHashMap<String, String>();
                resultItem.put("field_name", item.getFieldName());
                resultItem.put("file_name", filename);
                resultItem.put("content_type", item.getContentType());
                resultItem.put("size", Long.toString(item.getSize()));
                resultItem.put("session_key", sessionKey);

                resultFileElements.add(resultItem);

                index++;
            }
        }
    } catch (FileUploadException e) {
        logger.error("Unexpected file upload exception: " + e.getMessage(), e);
        throw new IOException(e);
    }

    final String contentType = req.getParameter("contentType");
    if (contentType == null) {
        resp.setContentType("application/json");
    } else {
        resp.setContentType(contentType);
    }

    final Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
    resultMap.put("status", "success");
    resultMap.put("files", resultFileElements);

    // write result as JSON
    final ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.writeValue(resp.getOutputStream(), resultMap);
}

From source file:org.debux.webmotion.server.handler.ParametersMultipartHandler.java

@Override
public void handle(Mapping mapping, Call call) {
    HttpContext context = call.getContext();
    HttpServletRequest request = context.getRequest();

    Map<String, Object> extractParameters = call.getExtractParameters();

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        FileItemFactory fileItemFactory = new DiskFileItemFactory(0, null);
        ServletFileUpload upload = new ServletFileUpload(fileItemFactory);

        HttpSession session = request.getSession();
        if (session != null) {
            log.debug("Set file upload listener");
            FileProgressListener listener = new FileProgressListener();
            upload.setProgressListener(listener);
            session.setAttribute(FileProgressListener.SESSION_ATTRIBUTE_NAME, listener);
            call.setFileUploadRequest(true);
        } else {/*from   w w  w  .ja v a  2s .  c  om*/
            log.warn("No session for file upload listener");
        }

        try {
            List<DiskFileItem> items = upload.parseRequest(request);
            for (DiskFileItem item : items) {
                String fieldName = item.getFieldName();

                if (item.isFormField()) {
                    String fieldValue;
                    try {
                        fieldValue = item.getString("UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        fieldValue = item.getString();
                    }

                    String[] values = (String[]) extractParameters.get(fieldName);
                    if (values == null) {
                        values = new String[] { fieldValue };
                        extractParameters.put(fieldName, values);

                    } else {
                        values = (String[]) ArrayUtils.add(values, fieldValue);
                        extractParameters.put(fieldName, values);
                    }

                } else {
                    UploadFile uploadFile = new UploadFile();

                    File file = item.getStoreLocation();
                    uploadFile.setFile(file);

                    String fileName = item.getName();
                    uploadFile.setName(fileName);

                    long fileSize = item.getSize();
                    uploadFile.setSize(fileSize);

                    String fileType = item.getContentType();
                    uploadFile.setContentType(fileType);

                    extractParameters.put(fieldName, uploadFile);
                }
            }
        } catch (FileUploadException fue) {
            throw new WebMotionException("Error during upload file on server", fue);
        }

    } else {
        Map<String, String[]> parameters = context.getParameters();
        extractParameters.putAll(parameters);
    }
}

From source file:org.eclipse.equinox.http.servlet.internal.multipart.MultipartSupportImpl.java

public Map<String, Part> parseRequest(HttpServletRequest request) throws IOException, ServletException {
    if (upload == null) {
        throw new IllegalStateException("Servlet was not configured for multipart!"); //$NON-NLS-1$
    }/*  w ww .  j  a  v  a  2  s  .c o m*/

    if (!servletDTO.multipartEnabled) {
        throw new IllegalStateException("No multipart config on " + servletDTO); //$NON-NLS-1$
    }

    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new ServletException("Not a multipart request!"); //$NON-NLS-1$
    }

    Map<String, Part> parts = new HashMap<String, Part>();

    try {
        for (Object item : upload.parseRequest(request)) {
            DiskFileItem diskFileItem = (DiskFileItem) item;

            parts.put(diskFileItem.getFieldName(), new MultipartSupportPart(diskFileItem));
        }
    } catch (FileUploadException fnfe) {
        throw new IOException(fnfe);
    }

    return parts;
}

From source file:org.infoglue.calendar.actions.CalendarUploadAbstractAction.java

public File getFile() {
    try {//from  w ww .j a v  a  2s  .  co m
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // Configure the factory here, if desired.
        PortletFileUpload upload = new PortletFileUpload(factory);
        // Configure the uploader here, if desired.
        List fileItems = upload.parseRequest(ServletActionContext.getRequest());
        log.debug("fileItems:" + fileItems.size());
        Iterator i = fileItems.iterator();
        while (i.hasNext()) {
            Object o = i.next();
            DiskFileItem dfi = (DiskFileItem) o;
            log.debug("dfi:" + dfi.getFieldName());
            log.debug("dfi:" + dfi);

            if (!dfi.isFormField()) {
                String fieldName = dfi.getFieldName();
                String fileName = dfi.getName();
                String contentType = dfi.getContentType();
                boolean isInMemory = dfi.isInMemory();
                long sizeInBytes = dfi.getSize();

                log.debug("fieldName:" + fieldName);
                log.debug("fileName:" + fileName);
                log.debug("contentType:" + contentType);
                log.debug("isInMemory:" + isInMemory);
                log.debug("sizeInBytes:" + sizeInBytes);
                File uploadedFile = new File(getTempFilePath() + File.separator + fileName);
                dfi.write(uploadedFile);
                return uploadedFile;
            }

        }

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

    return file;
}