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:fll.web.UploadProcessor.java

/**
 * Processes <code>request</code> as a file upload and puts the results back
 * in the <code>request</code> object. Each parameter that is a file upload
 * has a value of type {@link FileItem}. Other parameters have values of type
 * {@link String}./*from ww w .  j av a2  s. c  o  m*/
 * 
 * @param request
 */
public static void processUpload(final HttpServletRequest request) throws FileUploadException {
    // Parse the request
    final List<?> items = UPLOAD.parseRequest(request);
    final Iterator<?> iter = items.iterator();
    while (iter.hasNext()) {
        final FileItem item = (FileItem) iter.next();
        if (item.isFormField()) {
            request.setAttribute(item.getFieldName(), item.getString());
        } else {
            request.setAttribute(item.getFieldName(), item);
        }
    }
}

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

public static MultiPartData handleRequest(StringKey key, HttpServletRequest req) 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);

    MultiPartData data = new MultiPartData(key);

    // 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();
            data.addParam(name, value);// w  w  w  .  j a v  a 2  s  .c om
        } else {
            String fieldName = item.getFieldName();
            String fileName = item.getName();
            String contentType = item.getContentType();
            File uf = new File(ServerContext.getTempWorkDir(), System.currentTimeMillis() + ".upload");
            item.write(uf);
            data.addFile(fieldName, uf, fileName, contentType);
            StringKey fileKey = new StringKey(fileName, System.currentTimeMillis());
            CacheManager.getCache(Cache.TYPE_TEMP_FILE).put(fileKey, uf);
        }
    }
    return data;
}

From source file:com.pureinfo.srm.RequestUtils.java

public static PureProperties parse(HttpServletRequest _request) throws PureException {
    logger.debug("enti");
    PureProperties props = new PureProperties();

    Enumeration names = _request.getParameterNames();
    logger.debug("enti11111111111#" + names.hasMoreElements());
    while (names.hasMoreElements()) {
        String sName = (String) names.nextElement();
        String[] values = _request.getParameterValues(sName);
        if (values.length == 1) {
            props.setProperty(sName, values[0]);
        } else {//from w ww  .j  a v  a  2 s . co m
            props.setProperty(sName, values);
        }

    }

    String sContentType = _request.getContentType();
    if (sContentType != null && sContentType.startsWith("multipart/form-data")) {
        logger.debug("enti111");
        DiskFileUpload upload = new DiskFileUpload();
        List items;
        try {
            items = upload.parseRequest(_request);
        } catch (FileUploadException ex) {
            throw new PureException(PureException.UNKNOWN, "upload error", ex);
        }
        logger.debug("enti111111111111" + items.size());
        for (Iterator iter = items.iterator(); iter.hasNext();) {
            FileItem item = (FileItem) iter.next();
            if (item.getName() == null) {
                props.setProperty(item.getFieldName(), item.getString());
            } else {
                props.setProperty(item.getFieldName(), item);
            }
            logger.debug("name:" + item.getFieldName() + "-value:" + props.getProperty(item.getFieldName()));
        }
    }

    return props;
}

From source file:controller.file.FileUploader.java

public static void fileUploader(HttpServletRequest req, HttpServletResponse resp) {
    try {/* w ww  . j  a v a  2  s .co  m*/
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
        List<FileItem> items = servletFileUpload.parseRequest(req);
        Iterator<FileItem> iterator = items.iterator();
        while (iterator.hasNext()) {
            FileItem item = iterator.next();
            if (item.isFormField()) {

                String fileName = item.getFieldName();
                String value = item.getString();
                System.out.println(fileName);
                System.out.println(value);

            } else {
                if (!item.isFormField()) {
                    item.write(new File("/tmp/" + item.getName()));
                }
            }

        }
    } catch (FileUploadException ex) {
        Logger.getLogger(FileUploader.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(FileUploader.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:beans.service.FileUploadTool.java

static public String FileUpload(Map<String, String> fields, List<String> filesOnServer,
        HttpServletRequest request, HttpServletResponse response) {

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    DiskFileItemFactory factory = new DiskFileItemFactory();
    int MaxMemorySize = 10000000;
    int MaxRequestSize = MaxMemorySize;
    String tmpDir = System.getProperty("TMP", "/tmp");
    System.out.printf("temporary directory:%s", tmpDir);

    factory.setSizeThreshold(MaxMemorySize);
    factory.setRepository(new File(tmpDir));

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

    // Set overall request size constraint
    upload.setSizeMax(MaxRequestSize);/*from  w w  w .  ja  va 2s.  co  m*/

    // Parse the request
    try {
        List<FileItem> items = upload.parseRequest(request);
        // Process the uploaded items
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();
            if (item.isFormField()) {//k -v
                String name = item.getFieldName();
                String value = item.getString();
                fields.put(name, value);
            } else {

                String fieldName = item.getFieldName();
                String fileName = item.getName();
                if (fileName == null || fileName.length() < 1) {
                    return "file name is empty.";
                }
                String localFileName = ServletConfig.fileServerRootDir + File.separator + "tmp" + File.separator
                        + fileName;
                System.out.printf("upload file:%s", localFileName);
                String contentType = item.getContentType();
                boolean isInMemory = item.isInMemory();
                long sizeInBytes = item.getSize();
                File uploadedFile = new File(localFileName);
                item.write(uploadedFile);
                filesOnServer.add(localFileName);
            }

        }
        return "success";
    } catch (FileUploadException e) {
        e.printStackTrace();
        return e.toString();
    } catch (Exception e) {
        e.printStackTrace();
        return e.toString();
    }

}

From source file:com.dien.upload.server.UploadAction.java

/**
 * Returns the value of a text field present in the FileItem collection. 
 * //w w  w  .  ja  v  a2 s  .  c  o  m
 * @param sessionFiles collection of fields sent by the client 
 * @param fieldName field name 
 * @return the string value 
 */
public static String getFormField(Vector<FileItem> sessionFiles, String fieldName) {
    FileItem item = findItemByFieldName(sessionFiles, fieldName);
    return item == null || item.isFormField() == false ? null : item.getString();
}

From source file:com.uniquesoft.uidl.servlet.UploadAction.java

/**
 * Returns the value of a text field present in the FileItem collection. 
 * /*w w  w.  j  av  a 2  s  .  c om*/
 * @param sessionFiles collection of fields sent by the client 
 * @param fieldName field name 
 * @return the string value 
 */
public static String getFormField(List<FileItem> sessionFiles, String fieldName) {
    FileItem item = findItemByFieldName(sessionFiles, fieldName);
    return item == null || item.isFormField() == false ? null : item.getString();
}

From source file:com.founder.fix.fixflow.explorer.util.FileHandle.java

public static void whenUploadFileBindParameter(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    try {//  w w  w  .  jav a2  s  .  com
        fi.clear();
        fi.removeAll(fi);
        Iterator<FileItem> iterator = createFactory(request, response);
        while (iterator.hasNext()) {
            FileItem fileItem = (FileItem) iterator.next();
            if (fileItem.isFormField()) { // ??????
                String name = fileItem.getFieldName(); // inputname
                String value = fileItem.getString(); // input?value
                request.setAttribute(filterEncoding(name), filterEncoding(value));
            } else {
                fi.add(fileItem);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new Exception("??!");
    }
}

From source file:edu.isi.webserver.FileUtil.java

static public File downloadFileFromHTTPRequest(HttpServletRequest request) {
    // Download the file to the upload file folder
    File destinationDir = new File(DESTINATION_DIR_PATH);
    logger.info("File upload destination directory: " + destinationDir.getAbsolutePath());
    if (!destinationDir.isDirectory()) {
        destinationDir.mkdir();//from  w w w  .  j  ava 2s . co m
    }

    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();

    // Set the size threshold, above which content will be stored on disk.
    fileItemFactory.setSizeThreshold(1 * 1024 * 1024); //1 MB

    //Set the temporary directory to store the uploaded files of size above threshold.
    fileItemFactory.setRepository(destinationDir);

    ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);

    File uploadedFile = null;
    try {
        // Parse the request
        @SuppressWarnings("rawtypes")
        List items = uploadHandler.parseRequest(request);
        @SuppressWarnings("rawtypes")
        Iterator itr = items.iterator();
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();

            // Ignore Form Fields.
            if (item.isFormField()) {
                System.out.println(item.getFieldName());
                System.out.println(item.getString());
                // Do nothing
            } else {
                //Handle Uploaded files. Write file to the ultimate location.
                System.out.println("File field name: " + item.getFieldName());
                uploadedFile = new File(destinationDir, item.getName());
                item.write(uploadedFile);
                System.out.println("File written to: " + uploadedFile.getAbsolutePath());
            }
        }
    } catch (FileUploadException ex) {
        logger.error("Error encountered while parsing the request", ex);
    } catch (Exception ex) {
        logger.error("Error encountered while uploading file", ex);
    }
    return uploadedFile;
}

From source file:eu.impact_project.iif.t2.client.Helper.java

/**
 * Extracts all the form input values from a request object. Taverna
 * workflows are read as strings. Other files are converted to Base64
 * strings.//from  w  w w.jav  a  2  s.  c om
 * 
 * @param request
 *            The request object that will be analyzed
 * @return Map containing all form values and files as strings. The name of
 *         the form is used as the index
 */
public static Map<String, String> parseRequest(HttpServletRequest request) {

    // stores all the strings and encoded files from the html form
    Map<String, String> htmlFormItems = new HashMap<String, String>();
    try {

        // 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
        List items;
        items = upload.parseRequest(request);

        // Process the uploaded items
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            // a normal string field
            if (item.isFormField()) {

                // put the string items into the map
                htmlFormItems.put(item.getFieldName(), item.getString());

                // uploaded workflow file
            } else if (item.getFieldName().startsWith("file_workflow")) {

                htmlFormItems.put(item.getFieldName(), new String(item.get()));

                // uploaded file
            } else {

                // encode the uploaded file to base64
                String currentAttachment = new String(Base64.encode(item.get()));

                // put the encoded attachment into the map
                htmlFormItems.put(item.getFieldName(), currentAttachment);
            }
        }

    } catch (FileUploadException e) {
        e.printStackTrace();
    }
    return htmlFormItems;
}