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: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 w w  w .j  a  v a2  s.  com*/
 * 
 * @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);// ww  w.  j  a va 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.evanmclean.evlib.commons.fileupload.FileUploadUtils.java

/**
 * Remaps the file items returned by FileUpload.parseRequest into a map based
 * on the field names./*ww w . j a va  2 s  .co  m*/
 * 
 * @param file_items
 * @return A map keyed on the field name.
 */
public static Map<String, FileItem[]> mapItems(final List<?> file_items) {
    final Map<String, FileItem[]> map = new HashMap<String, FileItem[]>();
    for (Object object : file_items) {
        final FileItem fi = (FileItem) object;
        final String key = fi.getFieldName();
        FileItem[] arr = map.get(key);
        if (arr == null) {
            arr = new FileItem[1];
            arr[0] = fi;
        } else {
            final FileItem[] newarr = new FileItem[arr.length + 1];
            System.arraycopy(arr, 0, newarr, 0, arr.length);
            newarr[arr.length] = fi;
        }
        map.put(key, arr);
    }
    return map;
}

From source file:com.stratelia.webactiv.quizz.QuestionHelper.java

public static List<Answer> extractAnswer(List<FileItem> items, QuestionForm form, String componentId,
        String subdir) throws IOException {
    List<Answer> answers = new ArrayList<Answer>();
    Iterator<FileItem> iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();
        String mpName = item.getFieldName();
        if (item.isFormField() && mpName.startsWith("answer")) {
            String answerInput = FileUploadUtil.getOldParameter(items, mpName, "");
            Answer answer = new Answer(null, null, answerInput, 0, false, null, 0, false, null, null);
            String id = mpName.substring("answer".length());
            String nbPoints = FileUploadUtil.getOldParameter(items, "nbPoints" + id, "0");
            answer.setNbPoints(Integer.parseInt(nbPoints));
            if (Integer.parseInt(nbPoints) > 0) {
                answer.setIsSolution(true);
            }/* w ww  . ja v a 2 s.c  om*/
            String comment = FileUploadUtil.getOldParameter(items, "comment" + id, "");
            answer.setComment(comment);
            String value = FileUploadUtil.getOldParameter(items, "valueImageGallery" + id, "");
            if (StringUtil.isDefined(value)) {
                // traiter les images venant de la gallery si pas d'image externe
                if (!form.isFile()) {
                    answer.setImage(value);
                }
            }
            FileItem image = FileUploadUtil.getFile(items, "image" + id);
            if (image != null) {
                addImageToAnswer(answer, image, form, componentId, subdir);
            }
            answers.add(answer);
        }
    }
    return answers;
}

From source file:controller.file.FileUploader.java

public static void fileUploader(HttpServletRequest req, HttpServletResponse resp) {
    try {//  w w w  .  java 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: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 {/*  w w w .  j av  a  2s.  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:com.silverpeas.util.web.servlet.FileUploadUtil.java

public static FileItem getFile(List<FileItem> items, String parameterName) {
    for (FileItem item : items) {
        if (!item.isFormField() && parameterName.equals(item.getFieldName())) {
            return item;
        }//from   w  w  w.  j  ava 2s  .  com
    }
    return null;
}

From source file:com.silverpeas.util.web.servlet.FileUploadUtil.java

/**
 * Get the parameter value from the list of FileItems. Returns the defaultValue if the parameter
 * is not found./* w w  w.j  a va 2  s.  co m*/
 *
 * @param items the items resulting from parsing the request.
 * @param parameterName
 * @param defaultValue the value to be returned if the parameter is not found.
 * @param encoding the request encoding.
 * @return the parameter value from the list of FileItems. Returns the defaultValue if the
 * parameter is not found.
 */
public static String getParameter(List<FileItem> items, String parameterName, String defaultValue,
        String encoding) {
    for (FileItem item : items) {
        if (item.isFormField() && parameterName.equals(item.getFieldName())) {
            try {
                return item.getString(encoding);
            } catch (UnsupportedEncodingException e) {
                return item.getString();
            }
        }
    }
    return defaultValue;
}

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);// w  ww  .j  a va 2  s . c  om

    // 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.liferay.apio.architect.internal.body.MultipartToBodyConverter.java

/**
 * Reads a {@code "multipart/form"} HTTP request body into a {@link Body}
 * instance or fails with a {@link BadRequestException} if the input is not
 * a valid multipart form.// ww w .  j  av a 2s.co m
 *
 * @review
 */
public static Body multipartToBody(HttpServletRequest request) {
    if (!isMultipartContent(request)) {
        throw new BadRequestException("Request body is not a valid multipart form");
    }

    FileItemFactory fileItemFactory = new DiskFileItemFactory();

    ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);

    try {
        List<FileItem> fileItems = servletFileUpload.parseRequest(request);

        Iterator<FileItem> iterator = fileItems.iterator();

        Map<String, String> values = new HashMap<>();
        Map<String, BinaryFile> binaryFiles = new HashMap<>();
        Map<String, Map<Integer, String>> indexedValueLists = new HashMap<>();
        Map<String, Map<Integer, BinaryFile>> indexedFileLists = new HashMap<>();

        while (iterator.hasNext()) {
            FileItem fileItem = iterator.next();

            String name = fileItem.getFieldName();

            Matcher matcher = _arrayPattern.matcher(name);

            if (matcher.matches()) {
                int index = Integer.parseInt(matcher.group(2));

                String actualName = matcher.group(1);

                _storeFileItem(fileItem, value -> {
                    Map<Integer, String> indexedMap = indexedValueLists.computeIfAbsent(actualName,
                            __ -> new HashMap<>());

                    indexedMap.put(index, value);
                }, binaryFile -> {
                    Map<Integer, BinaryFile> indexedMap = indexedFileLists.computeIfAbsent(actualName,
                            __ -> new HashMap<>());

                    indexedMap.put(index, binaryFile);
                });
            } else {
                _storeFileItem(fileItem, value -> values.put(name, value),
                        binaryFile -> binaryFiles.put(name, binaryFile));
            }
        }

        Map<String, List<String>> valueLists = _flattenMap(indexedValueLists);

        Map<String, List<BinaryFile>> fileLists = _flattenMap(indexedFileLists);

        return Body.create(key -> Optional.ofNullable(values.get(key)),
                key -> Optional.ofNullable(valueLists.get(key)), key -> Optional.ofNullable(fileLists.get(key)),
                key -> Optional.ofNullable(binaryFiles.get(key)));
    } catch (FileUploadException | IndexOutOfBoundsException | NumberFormatException e) {

        throw new BadRequestException("Request body is not a valid multipart form", e);
    }
}