Example usage for org.apache.commons.fileupload FileItem getFieldName

List of usage examples for org.apache.commons.fileupload FileItem getFieldName

Introduction

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

Prototype

String getFieldName();

Source Link

Document

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

Usage

From source file:com.news.util.UploadFileUtil.java

public static String upload(HttpServletRequest request, String paramName, String fileName) {
    String result = "";
    File file;//  w ww  .ja va 2  s .c  o m
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    String filePath = "";
    ///opt/apache-tomcat-7.0.59/webapps/noithat
    //filePath = getServletContext().getRealPath("") + File.separator + "test-upload" + File.separator;
    filePath = File.separator + File.separator + "opt" + File.separator + File.separator;
    filePath += "apache-tomcat-7.0.59" + File.separator + File.separator + "webapps";
    filePath += File.separator + File.separator + "noithat";
    filePath += File.separator + File.separator + "upload" + File.separator + File.separator;
    filePath += "images" + File.separator;

    //filePath = "E:" + File.separator;

    // Verify the content type
    String contentType = request.getContentType();
    System.out.println("contentType=" + contentType);
    if (contentType != null && (contentType.indexOf("multipart/form-data") >= 0)) {

        DiskFileItemFactory factory = new DiskFileItemFactory();
        // maximum size that will be stored in memory
        factory.setSizeThreshold(maxMemSize);
        // Location to save data that is larger than maxMemSize.
        factory.setRepository(new File("c:\\temp"));

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // maximum file size to be uploaded.
        upload.setSizeMax(maxFileSize);
        try {
            // Parse the request to get file items.
            List fileItems = upload.parseRequest(request);
            System.out.println("fileItems.size()=" + fileItems.size());
            // Process the uploaded file items
            Iterator i = fileItems.iterator();

            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (!fi.isFormField() && fi.getFieldName().equals(paramName)) {
                    // Get the uploaded file parameters
                    String fieldName = fi.getFieldName();
                    int dotPos = fi.getName().lastIndexOf(".");
                    if (dotPos < 0) {
                        fileName += ".jpg";
                    } else {
                        fileName += fi.getName().substring(dotPos);
                    }
                    boolean isInMemory = fi.isInMemory();
                    long sizeInBytes = fi.getSize();
                    // Write the file
                    if (fileName.lastIndexOf("\\") >= 0) {
                        file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                    } else {
                        file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
                    }
                    fi.write(file);
                    System.out.println("Uploaded Filename: " + filePath + fileName + "<br>");
                    result = fileName;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    return result;
}

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  . java2s.  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:msec.org.FileUploadServlet.java

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

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();
    int MaxMemorySize = 10000000;
    int MaxRequestSize = MaxMemorySize;
    String tmpDir = System.getProperty("TMP", "/tmp");
    //System.out.printf("temporary directory:%s", tmpDir);

    // Set factory constraints
    factory.setSizeThreshold(MaxMemorySize);
    factory.setRepository(new File(tmpDir));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("utf8");

    // Set overall request size constraint
    upload.setSizeMax(MaxRequestSize);/* w w  w .ja  v a2  s  .  c om*/

    // Parse the request
    try {
        @SuppressWarnings("unchecked")
        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("utf-8");
                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.gtwm.pb.servlets.ServletUtilMethods.java

/**
 * Replacement for and wrapper around//  www .ja  v  a 2  s.  co m
 * HttpServletRequest.getParameter(String) which works for multi-part form
 * data as well as normal requests
 */
public static String getParameter(HttpServletRequest request, String parameterName,
        List<FileItem> multipartItems) {
    if (FileUpload.isMultipartContent(new ServletRequestContext(request))) {
        for (FileItem item : multipartItems) {
            if (item.getFieldName().equals(parameterName)) {
                if (item.isFormField()) {
                    return item.getString();
                } else {
                    return item.getName();
                }
            }
        }
        return null;
    } else {
        return request.getParameter(parameterName);
    }
}

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();/*  w  ww  . j  a va 2 s  .  com*/
    }

    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:edu.cornell.mannlib.vitro.webapp.controller.MultipartRequestWrapper.java

private static void parseFileParts(HttpServletRequest req, ListsMap<String> parameters,
        ListsMap<FileItem> files, ParsingStrategy strategy) throws IOException {

    ServletFileUpload upload = createUploadHandler(req, strategy.maximumMultipartFileSize());
    List<FileItem> items = parseRequestIntoFileItems(req, upload, strategy);

    for (FileItem item : items) {
        // Process a regular form field
        String name = item.getFieldName();
        if (item.isFormField()) {
            String value;/*w  w  w  . ja  va 2  s . c  o m*/
            try {
                value = item.getString("UTF-8");
            } catch (UnsupportedEncodingException e) {
                value = item.getString();
            }
            parameters.add(name, value);
            log.debug("Form field (parameter) " + name + "=" + value);
        } else {
            files.add(name, item);
            log.debug("File " + name + ": " + item.getSize() + " bytes.");
        }
    }
}

From source file:com.openmeap.util.ServletUtils.java

/**
 * @param modelManager/*from www  . j  av  a2  s .c o m*/
 * @param request
 * @param map
 * @return
 * @throws FileUploadException
 */
static final public Boolean handleFileUploads(Integer maxFileUploadSize, String fileStoragePrefix,
        HttpServletRequest request, Map<Object, Object> map) throws FileUploadException {

    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(4096);
    factory.setRepository(new File(fileStoragePrefix));

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(maxFileUploadSize);

    List fileItems = upload.parseRequest(request);
    for (FileItem item : (List<FileItem>) fileItems) {
        // we'll put this in the parameter map,
        // assuming the backing that is looking for it
        // knows what to expect
        String fieldName = item.getFieldName();
        Boolean isFormField = item.isFormField();
        Long size = item.getSize();
        if (isFormField) {
            if (size > 0) {
                map.put(fieldName, new String[] { item.getString() });
            }
        } else if (!isFormField) {
            map.put(fieldName, item);
        }
    }

    return true;
}

From source file:dataMappers.PictureDataMapper.java

public static void addPictureToReport(DBConnector dbconnector, HttpServletRequest request)
        throws FileUploadException, IOException, SQLException {

    if (!ServletFileUpload.isMultipartContent(request)) {
        System.out.println("Invalid upload request");
        return;//  www. j a v a  2s  .  co  m
    }

    // Define limits for disk item
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(THRESHOLD_SIZE);

    // Define limit for servlet upload
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(MAX_FILE_SIZE);
    upload.setSizeMax(MAX_REQUEST_SIZE);

    FileItem itemFile = null;
    int reportID = 0;

    // Get list of items in request (parameters, files etc.)
    List formItems = upload.parseRequest(request);
    Iterator iter = formItems.iterator();

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

        if (!item.isFormField()) {
            itemFile = item; // If not form field, must be item
        } else if (item.getFieldName().equalsIgnoreCase("reportID")) { // else it is a form field
            try {
                System.out.println(item.getString());
                reportID = Integer.parseInt(item.getString());
            } catch (NumberFormatException e) {
                reportID = 0;
            }
        }
    }

    // This will be null if no fields were declared as image/upload.
    // Also, reportID must be > 0
    if (itemFile != null || reportID == 0) {

        try {

            // Create credentials from final vars
            BasicAWSCredentials awsCredentials = new BasicAWSCredentials(AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY);

            // Create client with credentials
            AmazonS3 s3client = new AmazonS3Client(awsCredentials);
            // Set region
            s3client.setRegion(Region.getRegion(Regions.EU_WEST_1));

            // Set content length (size) of file
            ObjectMetadata om = new ObjectMetadata();
            om.setContentLength(itemFile.getSize());

            // Get extension for file
            String ext = FilenameUtils.getExtension(itemFile.getName());
            // Generate random filename
            String keyName = UUID.randomUUID().toString() + '.' + ext;

            // This is the actual upload command
            s3client.putObject(new PutObjectRequest(S3_BUCKET_NAME, keyName, itemFile.getInputStream(), om));

            // Picture was uploaded to S3 if we made it this far. Now we insert the row into the database for the report.
            PreparedStatement stmt = dbconnector.getCon()
                    .prepareStatement("INSERT INTO reports_pictures" + "(REPORTID, PICTURE) VALUES (?,?)");

            stmt.setInt(1, reportID);
            stmt.setString(2, keyName);

            stmt.executeUpdate();

            stmt.close();

        } catch (AmazonServiceException ase) {

            System.out.println("Caught an AmazonServiceException, which " + "means your request made it "
                    + "to Amazon S3, but was rejected with an error response" + " for some reason.");
            System.out.println("Error Message:    " + ase.getMessage());
            System.out.println("HTTP Status Code: " + ase.getStatusCode());
            System.out.println("AWS Error Code:   " + ase.getErrorCode());
            System.out.println("Error Type:       " + ase.getErrorType());
            System.out.println("Request ID:       " + ase.getRequestId());

        } catch (AmazonClientException ace) {

            System.out.println("Caught an AmazonClientException, which " + "means the client encountered "
                    + "an internal error while trying to " + "communicate with S3, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message: " + ace.getMessage());

        }

    }
}

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.// w ww.ja  v 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;
}

From source file:com.silverpeas.util.i18n.I18NHelper.java

static private String getParameterValue(List<FileItem> items, String parameterName) {
    for (FileItem item : items) {
        if (item.isFormField() && parameterName.equals(item.getFieldName())) {
            return item.getString();
        }//from   w  ww  .jav  a  2s . co  m
    }
    return null;
}