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(String encoding) throws UnsupportedEncodingException;

Source Link

Document

Returns the contents of the file item as a String, using the specified encoding.

Usage

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./*from   w  w w . ja  v a  2  s. c o  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: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);//from   w  ww.j a  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:fr.paris.lutece.util.http.MultipartUtil.java

/**
 * Convert a HTTP request to a {@link MultipartHttpServletRequest}
 * @param nSizeThreshold the size threshold
 * @param nRequestSizeMax the request size max
 * @param bActivateNormalizeFileName true if the file name must be normalized, false otherwise
 * @param request the HTTP request/* ww  w. j a va 2 s  . c om*/
 * @return a {@link MultipartHttpServletRequest}, null if the request does not have a multipart content
 * @throws SizeLimitExceededException exception if the file size is too big
 * @throws FileUploadException exception if an unknown error has occurred
 */
public static MultipartHttpServletRequest convert(int nSizeThreshold, long nRequestSizeMax,
        boolean bActivateNormalizeFileName, HttpServletRequest request)
        throws SizeLimitExceededException, FileUploadException {
    if (isMultipart(request)) {
        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // Set factory constraints
        factory.setSizeThreshold(nSizeThreshold);

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

        // Set overall request size constraint
        upload.setSizeMax(nRequestSizeMax);

        // get encoding to be used
        String strEncoding = request.getCharacterEncoding();

        if (strEncoding == null) {
            strEncoding = EncodingService.getEncoding();
        }

        Map<String, FileItem> mapFiles = new HashMap<String, FileItem>();
        Map<String, String[]> mapParameters = new HashMap<String, String[]>();

        List<FileItem> listItems = upload.parseRequest(request);

        // Process the uploaded items
        for (FileItem item : listItems) {
            if (item.isFormField()) {
                String strValue = StringUtils.EMPTY;

                try {
                    if (item.getSize() > 0) {
                        strValue = item.getString(strEncoding);
                    }
                } catch (UnsupportedEncodingException ex) {
                    if (item.getSize() > 0) {
                        // if encoding problem, try with system encoding
                        strValue = item.getString();
                    }
                }

                // check if item of same name already in map
                String[] curParam = mapParameters.get(item.getFieldName());

                if (curParam == null) {
                    // simple form field
                    mapParameters.put(item.getFieldName(), new String[] { strValue });
                } else {
                    // array of simple form fields
                    String[] newArray = new String[curParam.length + 1];
                    System.arraycopy(curParam, 0, newArray, 0, curParam.length);
                    newArray[curParam.length] = strValue;
                    mapParameters.put(item.getFieldName(), newArray);
                }
            } else {
                // multipart file field, if the parameter filter ActivateNormalizeFileName is set to true
                //all file name will be normalize
                mapFiles.put(item.getFieldName(),
                        bActivateNormalizeFileName ? new NormalizeFileItem(item) : item);
            }
        }

        return new MultipartHttpServletRequest(request, mapFiles, mapParameters);
    }

    return null;
}

From source file:net.ontopia.topicmaps.webed.impl.utils.ReqParamUtils.java

/**
 * INTERNAL: Builds the Parameters object from an HttpServletRequest
 * object.// w ww  .  ja va 2  s  .  c  o m
 * @since 2.0
 */
public static Parameters decodeParameters(HttpServletRequest request, String charenc)
        throws ServletException, IOException {

    String ctype = request.getHeader("content-type");
    log.debug("Content-type: " + ctype);
    Parameters params = new Parameters();

    if (ctype != null && ctype.startsWith("multipart/form-data")) {
        // special file upload request, so use FileUpload to decode
        log.debug("Decoding with FileUpload; charenc=" + charenc);
        try {
            FileUpload upload = new FileUpload(new DefaultFileItemFactory());
            Iterator iterator = upload.parseRequest(request).iterator();
            while (iterator.hasNext()) {
                FileItem item = (FileItem) iterator.next();
                log.debug("Reading: " + item);
                if (item.isFormField()) {
                    if (charenc != null)
                        params.addParameter(item.getFieldName(), item.getString(charenc));
                    else
                        params.addParameter(item.getFieldName(), item.getString());
                } else
                    params.addParameter(item.getFieldName(), new FileParameter(item));
            }
        } catch (FileUploadException e) {
            throw new ServletException(e);
        }

    } else {
        // ordinary web request, so retrieve info and stuff into Parameters object
        log.debug("Normal parameter decode, charenc=" + charenc);
        if (charenc != null)
            request.setCharacterEncoding(charenc);
        Enumeration enumeration = request.getParameterNames();
        while (enumeration.hasMoreElements()) {
            String param = (String) enumeration.nextElement();
            params.addParameter(param, request.getParameterValues(param));
        }
    }

    return params;
}

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;/*from  ww  w  .j  av a 2 s  . co 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.fjn.helper.common.io.file.common.FileUpAndDownloadUtil.java

/**
 * ???????//from www .  j av  a 2 s  .  co m
 * @param klass   ???klass?Class
 * @param filepath   ?
 * @param sizeThreshold   ??
 * @param isFileNameBaseTime   ????
 * @return bean
 */
public static <T> Object upload(HttpServletRequest request, Class<T> klass, String filepath, int sizeThreshold,
        boolean isFileNameBaseTime) throws Exception {
    FileItemFactory fileItemFactory = null;
    if (sizeThreshold > 0) {
        File repository = new File(filepath);
        fileItemFactory = new DiskFileItemFactory(sizeThreshold, repository);
    } else {
        fileItemFactory = new DiskFileItemFactory();
    }
    ServletFileUpload upload = new ServletFileUpload(fileItemFactory);
    ServletRequestContext requestContext = new ServletRequestContext(request);
    T bean = null;
    if (klass != null) {
        bean = klass.newInstance();
    }
    // 
    if (ServletFileUpload.isMultipartContent(requestContext)) {
        File parentDir = new File(filepath);

        List<FileItem> fileItemList = upload.parseRequest(requestContext);
        for (int i = 0; i < fileItemList.size(); i++) {
            FileItem item = fileItemList.get(i);
            // ??
            if (item.isFormField()) {
                String paramName = item.getFieldName();
                String paramValue = item.getString("UTF-8");
                log.info("?" + paramName + "=" + paramValue);
                request.setAttribute(paramName, paramValue);
                // ?bean
                if (klass != null) {
                    Field field = null;
                    try {
                        field = klass.getDeclaredField(paramName);

                        if (field != null) {
                            field.setAccessible(true);
                            Class type = field.getType();
                            if (type == Integer.TYPE) {
                                field.setInt(bean, Integer.valueOf(paramValue));
                            } else if (type == Double.TYPE) {
                                field.setDouble(bean, Double.valueOf(paramValue));
                            } else if (type == Float.TYPE) {
                                field.setFloat(bean, Float.valueOf(paramValue));
                            } else if (type == Boolean.TYPE) {
                                field.setBoolean(bean, Boolean.valueOf(paramValue));
                            } else if (type == Character.TYPE) {
                                field.setChar(bean, paramValue.charAt(0));
                            } else if (type == Long.TYPE) {
                                field.setLong(bean, Long.valueOf(paramValue));
                            } else if (type == Short.TYPE) {
                                field.setShort(bean, Short.valueOf(paramValue));
                            } else {
                                field.set(bean, paramValue);
                            }
                        }
                    } catch (NoSuchFieldException e) {
                        log.info("" + klass.getName() + "?" + paramName);
                    }
                }
            }
            // 
            else {
                // <input type='file' name='xxx'> xxx
                String paramName = item.getFieldName();
                log.info("?" + item.getSize());

                if (sizeThreshold > 0) {
                    if (item.getSize() > sizeThreshold)
                        continue;
                }
                String clientFileName = item.getName();
                int index = -1;
                // ?IE?
                if ((index = clientFileName.lastIndexOf("\\")) != -1) {
                    clientFileName = clientFileName.substring(index + 1);
                }
                if (clientFileName == null || "".equals(clientFileName))
                    continue;

                String filename = null;
                log.info("" + paramName + "\t??" + clientFileName);
                if (isFileNameBaseTime) {
                    filename = buildFileName(clientFileName);
                } else
                    filename = clientFileName;

                request.setAttribute(paramName, filename);

                // ?bean
                if (klass != null) {
                    Field field = null;
                    try {
                        field = klass.getDeclaredField(paramName);
                        if (field != null) {
                            field.setAccessible(true);
                            field.set(bean, filename);
                        }
                    } catch (NoSuchFieldException e) {
                        log.info("" + klass.getName() + "?  " + paramName);
                        continue;
                    }
                }

                if (!parentDir.exists()) {
                    parentDir.mkdirs();
                }

                File newfile = new File(parentDir, filename);
                item.write(newfile);
                String serverPath = newfile.getPath();
                log.info("?" + serverPath);
            }
        }
    }
    return bean;
}

From source file:jeeves.server.sources.ServiceRequestFactory.java

private static Element getMultipartParams(HttpServletRequest req, String uploadDir, int maxUploadSize)
        throws Exception {
    Element params = new Element("params");

    DiskFileItemFactory fif = new DiskFileItemFactory();
    ServletFileUpload sfu = new ServletFileUpload(fif);

    sfu.setSizeMax(((long) maxUploadSize) * 1024L * 1024L);

    try {// ww w.j  a  v  a  2  s  . com
        for (Object i : sfu.parseRequest(req)) {
            FileItem item = (FileItem) i;
            String name = item.getFieldName();

            if (item.isFormField()) {
                String encoding = req.getCharacterEncoding();
                params.addContent(new Element(name).setText(item.getString(encoding)));
            } else {
                String file = item.getName();
                String type = item.getContentType();
                long size = item.getSize();

                if (Log.isDebugEnabled(Log.REQUEST))
                    Log.debug(Log.REQUEST, "Uploading file " + file + " type: " + type + " size: " + size);
                //--- remove path information from file (some browsers put it, like IE)

                file = simplifyName(file);
                if (Log.isDebugEnabled(Log.REQUEST))
                    Log.debug(Log.REQUEST, "File is called " + file + " after simplification");

                //--- we could get troubles if 2 users upload files with the same name
                item.write(new File(uploadDir, file));

                Element elem = new Element(name).setAttribute("type", "file")
                        .setAttribute("size", Long.toString(size)).setText(file);

                if (type != null)
                    elem.setAttribute("content-type", type);

                if (Log.isDebugEnabled(Log.REQUEST))
                    Log.debug(Log.REQUEST, "Adding to parameters: " + Xml.getString(elem));
                params.addContent(elem);
            }
        }
    } catch (FileUploadBase.SizeLimitExceededException e) {
        throw new FileUploadTooBigEx();
    }

    return params;
}

From source file:com.krawler.esp.handlers.fileUploader.java

public static void parseRequest(HttpServletRequest request, HashMap<String, String> arrParam,
        ArrayList<FileItem> fi, boolean fileUpload, HashMap<Integer, String> filemap) throws ServiceException {
    DiskFileUpload fu = new DiskFileUpload();
    FileItem fi1 = null;
    List fileItems = null;// ww  w .  j a  va2s.c  o m
    int i = 0;
    try {
        fileItems = fu.parseRequest(request);
    } catch (FileUploadException e) {
        throw ServiceException.FAILURE("Admin.createUser", e);
    }
    for (Iterator k = fileItems.iterator(); k.hasNext();) {
        fi1 = (FileItem) k.next();
        try {
            if (fi1.isFormField()) {
                arrParam.put(fi1.getFieldName(), fi1.getString("UTF-8"));
            } else {

                String fileName = new String(fi1.getName().getBytes(), "UTF8");
                if (fi1.getSize() != 0) {
                    fi.add(fi1);
                    filemap.put(i, fi1.getFieldName());
                    i++;
                    fileUpload = true;
                }
            }
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:com.easyjf.web.core.FrameworkEngine.java

/**
 * ?requestform//from ww  w .  ja va 2 s.  c  o  m
 * 
 * @param request
 * @param formName
 * @return ??Form
 */
public static WebForm creatWebForm(HttpServletRequest request, String formName, Module module) {
    Map textElement = new HashMap();
    Map fileElement = new HashMap();
    String contentType = request.getContentType();
    String reMethod = request.getMethod();
    if ((contentType != null) && (contentType.startsWith("multipart/form-data"))
            && (reMethod.equalsIgnoreCase("post"))) {
        //  multipart/form-data
        File file = new File(request.getSession().getServletContext().getRealPath("/temp"));
        if (!file.exists()) {
            file.getParentFile().mkdirs();
        }
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(webConfig.getUploadSizeThreshold());
        factory.setRepository(file);
        ServletFileUpload sf = new ServletFileUpload(factory);
        sf.setSizeMax(webConfig.getMaxUploadFileSize());
        sf.setHeaderEncoding(request.getCharacterEncoding());
        List reqPars = null;
        try {
            reqPars = sf.parseRequest(request);
            for (int i = 0; i < reqPars.size(); i++) {
                FileItem it = (FileItem) reqPars.get(i);
                if (it.isFormField()) {
                    textElement.put(it.getFieldName(), it.getString(request.getCharacterEncoding()));// ??
                } else {
                    fileElement.put(it.getFieldName(), it);// ???
                }
            }
        } catch (Exception e) {
            logger.error(e);
        }
    } else if ((contentType != null) && contentType.equals("text/xml")) {
        StringBuffer buffer = new StringBuffer();
        try {
            String s = request.getReader().readLine();
            while (s != null) {
                buffer.append(s + "\n");
                s = request.getReader().readLine();
            }
        } catch (Exception e) {
            logger.error(e);
        }
        textElement.put("xml", buffer.toString());
    } else {
        textElement = request2map(request);
    }
    // logger.debug("????");
    WebForm wf = findForm(formName);
    wf.setValidate(module.isValidate());// ?validate?Form
    if (wf != null) {
        wf.setFileElement(fileElement);
        wf.setTextElement(textElement);
    }
    return wf;
}

From source file:com.fjn.helper.common.io.file.upload.FileUploadHelper.java

/**
 * ?request?fireDir?request.setAttribute(fieldName, value)?
 *
 * @param request /*from   w  ww .  jav  a 2 s .  co m*/
 * @param fileDir 
 * @param maxSize ?
 * @param isFileNameBaseTime ????
 * @param encoding
 */
public static FileUploadRequestParamterContext upload(HttpServletRequest request, String fileDir, int maxSize,
        boolean isFileNameBaseTime, String encoding) {
    // ?
    if (!isFileUploadRequest(request))
        return null;
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // dir??
    File dir = new File(fileDir);
    if (!dir.exists()) {
        if (dir.mkdirs()) {
            throw new FileDirFaultException(dir);
        }
        ;
    }
    if (maxSize > 0) {
        factory.setSizeThreshold(maxSize);
    }

    factory.setRepository(dir);

    // ?
    ServletFileUpload fileUploader = new ServletFileUpload(factory);
    fileUploader.setHeaderEncoding(encodingCheck(encoding) ? encoding : defaultEncoding);
    String realEncoding = fileUploader.getHeaderEncoding();

    List<FileItem> items = null;
    try {
        items = fileUploader.parseRequest(request);
    } catch (FileUploadException e1) {
        e1.printStackTrace();
    }
    if (items == null)
        return null;

    FileUploadRequestParamterContext context = new FileUploadRequestParamterContext();
    Map<String, List<File>> fileMap = context.getFileMap();
    Map<String, List<String>> fieldMap = context.getFormFieldMap();

    FileItem fileItem = null;
    Iterator<FileItem> iter = items.iterator();
    while (iter.hasNext()) {
        fileItem = iter.next();
        String fieldName = fileItem.getFieldName();
        if (fileItem.isFormField()) {
            List<String> values = fieldMap.get(fieldName);
            if (values == null) {
                values = new ArrayList<String>();
                fieldMap.put(fieldName, values);
            }
            String value = null;
            try {
                value = fileItem.getString(realEncoding);
            } catch (UnsupportedEncodingException e) {
                value = "";
                e.printStackTrace();
            }
            values.add(value);
            log.info("param:\t" + fieldName + "=" + value);
        } else {
            List<File> files = fileMap.get(fieldName);
            if (files == null) {
                files = new ArrayList<File>();
                fileMap.put(fieldName, files);
            }

            String clientFileName = fileItem.getName();// ???
            if (StringUtil.isNull(clientFileName)) { // 
                continue;
            }
            String realFileName = FileUtil.getRealFileName(clientFileName);
            String newFileName = null;
            if (isFileNameBaseTime) {
                newFileName = new FileNameBuilder().build(realFileName);
            } else {
                newFileName = realFileName;
            }
            File tempfile = new File(dir, newFileName);
            try {
                fileItem.write(tempfile);
                log.info("???\t" + newFileName);
                files.add(tempfile);
            } catch (Exception e) {
                continue;
            }
        }
    }

    return null;
}