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:jeeves.server.sources.JeevletServiceRequestFactory.java

private static Element getMultipartParams(Request req, String uploadDir, int maxUploadSize) throws Exception {

    Element params = new Element("params");

    // FIXME FileUpload - confirm only "multipart/form-data" entities must be parsed here ...
    // if (entity != null && MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) {

    // The Apache FileUpload project parses HTTP requests which
    // conform to RFC 1867, "Form-based File Upload in HTML". That
    // is, if an HTTP request is submitted using the POST method,
    // and with a content type of "multipart/form-data", then
    // FileUpload can parse that request, and get all uploaded files
    // as FileItem.

    // 1/ Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(1000240); // en mmoire
    factory.setRepository(new File(uploadDir));

    // 2/ Create a new file upload handler based on the Restlet
    // FileUpload extension that will parse Restlet requests and
    // generates FileItems.
    RestletFileUpload upload = new RestletFileUpload(factory);

    upload.setFileSizeMax(maxUploadSize * 1024 * 1024);

    List<FileItem> items;/* w w w . j a va  2  s  .  c  om*/
    try {
        items = upload.parseRequest(req);// parseRepresentation(req.getEntity());

        for (final Iterator<FileItem> it = items.iterator(); it.hasNext();) {
            FileItem item = (FileItem) it.next();

            String name = item.getFieldName();

            if (item.isFormField())
                params.addContent(new Element(name).setText(item.getString()));
            else {
                String file = item.getName();
                String type = item.getContentType();
                long size = item.getSize();
                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);
                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);

                Log.debug(Log.REQUEST, "Adding to parameters: " + Xml.getString(elem));
                params.addContent(elem);
            }
        }
    } catch (FileUploadBase.FileSizeLimitExceededException e) {
        // throw jeeves exception --> reached code ? see apache docs -
        // FileUploadBase
        throw new FileUploadTooBigEx();
    } catch (FileUploadException e) {
        // Sample Restlet ... " 

        // The message of all thrown exception is sent back to client as simple plain text
        // response.setEntity(new StringRepresentation(e.getMessage(), MediaType.TEXT_PLAIN));
        // response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
        // e.printStackTrace();

        // " ... now throw a JeevletException but
        // FIXME must throw Exception with a correct Status
        throw new JeevletException(e);
    }

    return params;
}

From source file:dk.clarin.tools.userhandle.java

public static String getParmFromMultipartFormData(HttpServletRequest request, List<FileItem> items,
        String parm) {/*from  w w  w . j  ava2 s  .  c om*/
    logger.debug("parm:[" + parm + "]");
    String userHandle = "";
    boolean is_multipart_formData = ServletFileUpload.isMultipartContent(request);

    if (is_multipart_formData) {
        try {
            /*
            logger.debug("In try");
            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.
            * /
            logger.debug("making tmpDir in " + ToolsProperties.tempdir);
            File tmpDir = new File(ToolsProperties.tempdir);
            if(!tmpDir.isDirectory()) 
            {
            logger.debug("!tmpDir.isDirectory()");
            throw new ServletException("Trying to set \"" + ToolsProperties.tempdir + "\" as temporary directory, but this is not a valid directory.");
            }
            fileItemFactory.setRepository(tmpDir);
            * /
                    
            ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
            logger.debug("Now uploadHandler.parseRequest");
            List items<FileItem> = uploadHandler.parseRequest(request);
            */
            logger.debug("items:" + items);
            Iterator<FileItem> itr = items.iterator();
            logger.debug("itr:" + itr);
            while (itr.hasNext()) {
                logger.debug("in loop");
                FileItem item = (FileItem) itr.next();
                /*
                * Handle Form Fields.
                */
                if (item.isFormField()) {
                    logger.debug("Field Name = " + item.getFieldName() + ", String = " + item.getString());
                    if (item.getFieldName().equals(parm)) {
                        userHandle = item.getString();
                        logger.debug("Found " + parm + " = " + userHandle);
                        /*
                        if(userId == null && userHandle != null)
                        userId = userhandle.getUserId(request,userHandle);
                        if(userEmail == null && userId != null)
                        userEmail = userhandle.getEmailAddress(request,userHandle,userId);
                        */
                        break; // currently not interested in other fields than parm
                    }
                } else if (item.getName() != "") {
                    /*
                    * Write file to the ultimate location.
                    */
                    logger.debug("File = " + item.getName());
                    /* We don't handle file upload here
                    data = item.getName();
                    File file = new File(destinationDir,item.getName());
                    item.write(file);
                    */
                    logger.debug("FieldName = " + item.getFieldName());
                    logger.debug("Name = " + item.getName());
                    logger.debug("ContentType = " + item.getContentType());
                    logger.debug("Size = " + item.getSize());
                    logger.debug("DestinationDir = "
                            + ToolsProperties.documentRoot /*+ ToolsProperties.stagingArea*/);
                }
            }
        } catch (Exception ex) {
            logger.error("uploadHandler.parseRequest Exception");
        }
    } else {
        @SuppressWarnings("unchecked")
        Enumeration<String> parmNames = (Enumeration<String>) request.getParameterNames();

        for (Enumeration<String> e = parmNames; e.hasMoreElements();) {
            // Well, you don't get here AT ALL if enctype='multipart/form-data'
            String parmName = e.nextElement();
            logger.debug("parmName:" + parmName);
            String vals[] = request.getParameterValues(parmName);
            for (int j = 0; j < vals.length; ++j) {
                logger.debug("val:" + vals[j]);
            }
        }
    }
    logger.debug("value[" + parm + "]=" + userHandle);
    return userHandle;
}

From source file:com.zimbra.cs.servlet.util.CsrfUtil.java

public static boolean checkCsrfInMultipartFileUpload(List<FileItem> items, AuthToken at) {
    for (FileItem item : items) {
        if (item.isFormField()) {
            if (item.getFieldName().equals(PARAM_CSRF_TOKEN)) {
                if (item.getSize() < 128) { // if the value is larger, it is not a CSRF token
                    String csrfToken = item.getString();
                    if (CsrfUtil.isValidCsrfToken(csrfToken, at)) {
                        return true;
                    } else {
                        ZimbraLog.misc.debug("Csrf token : %s recd in file upload is invalid.", csrfToken);
                    }//from   ww  w  .  java2 s .c  o  m
                }
                break;
            }
        }
    }
    return false;
}

From source file:com.zlfun.framework.misc.UploadUtils.java

public static byte[] getFileBytes(HttpServletRequest request) {

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    // ???//  ww  w.  j  a  va 2  s  . c  o  m
    // ??
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // ??

    //  ?? 
    factory.setSizeThreshold(1024 * 1024);

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("UTF-8");
    try {
        // ?
        List<FileItem> list = (List<FileItem>) upload.parseRequest(request);

        for (FileItem item : list) {
            // ????
            String name = item.getFieldName();

            // ? ??  ?
            if (item.isFormField()) {
                // ? ?????? 
                String value = new String(item.getString().getBytes("iso-8859-1"), "utf-8");

                request.setAttribute(name, value);
            } // ? ??  
            else {
                /**
                 * ?? ??
                 */
                // ???
                String value = item.getName();
                // ?
                // ????
                value = java.net.URLDecoder.decode(value, "UTF-8");
                int start = value.lastIndexOf("\\");
                // ?  ??1 ???
                String filename = value.substring(start + 1);

                InputStream in = item.getInputStream();
                int length = 0;
                byte[] buf = new byte[1024];
                System.out.println("??" + item.getSize());
                // in.read(buf) ?? buf 
                while ((length = in.read(buf)) != -1) {
                    //  buf  ??  ??
                    out.write(buf, 0, length);
                }

                try {

                    if (in != null) {
                        in.close();
                    }

                } catch (IOException ex) {
                    Logger.getLogger(UploadUtils.class.getName()).log(Level.SEVERE, null, ex);
                }
                return out.toByteArray();

            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        try {
            out.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            Logger.getLogger(UploadUtils.class.getName()).log(Level.SEVERE, null, e);
        }
    }
    return null;

}

From source file:com.groupon.odo.HttpUtilities.java

/**
 * Sets up the given {@link org.apache.commons.httpclient.methods.PostMethod} to send the same multipart POST data
 * as was sent in the given {@link HttpServletRequest}
 *
 * @param postMethodProxyRequest The {@link org.apache.commons.httpclient.methods.PostMethod} that we are configuring to send a
 *                               multipart POST request
 * @param httpServletRequest     The {@link HttpServletRequest} that contains the multipart
 *                               POST data to be sent via the {@link org.apache.commons.httpclient.methods.PostMethod}
 *//*from w w w.j  a v  a  2s . c  om*/
@SuppressWarnings("unchecked")
public static void handleMultipartPost(EntityEnclosingMethod postMethodProxyRequest,
        HttpServletRequest httpServletRequest, DiskFileItemFactory diskFileItemFactory)
        throws ServletException {

    // Create a new file upload handler
    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
    // Parse the request
    try {
        // Get the multipart items as a list
        List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest);
        // Create a list to hold all of the parts
        List<Part> listParts = new ArrayList<Part>();
        // Iterate the multipart items list
        for (FileItem fileItemCurrent : listFileItems) {
            // If the current item is a form field, then create a string
            // part
            if (fileItemCurrent.isFormField()) {
                StringPart stringPart = new StringPart(fileItemCurrent.getFieldName(), // The field name
                        fileItemCurrent.getString() // The field value
                );
                // Add the part to the list
                listParts.add(stringPart);
            } else {
                // The item is a file upload, so we create a FilePart
                FilePart filePart = new FilePart(fileItemCurrent.getFieldName(), // The field name
                        new ByteArrayPartSource(fileItemCurrent.getName(), // The uploaded file name
                                fileItemCurrent.get() // The uploaded file contents
                        ));
                // Add the part to the list
                listParts.add(filePart);
            }
        }
        MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(
                listParts.toArray(new Part[listParts.size()]), postMethodProxyRequest.getParams());

        postMethodProxyRequest.setRequestEntity(multipartRequestEntity);

        // The current content-type header (received from the client) IS of
        // type "multipart/form-data", but the content-type header also
        // contains the chunk boundary string of the chunks. Currently, this
        // header is using the boundary of the client request, since we
        // blindly copied all headers from the client request to the proxy
        // request. However, we are creating a new request with a new chunk
        // boundary string, so it is necessary that we re-set the
        // content-type string to reflect the new chunk boundary string
        postMethodProxyRequest.setRequestHeader(STRING_CONTENT_TYPE_HEADER_NAME,
                multipartRequestEntity.getContentType());
    } catch (FileUploadException fileUploadException) {
        throw new ServletException(fileUploadException);
    }
}

From source file:com.krawler.esp.servlets.SuperAdminServlet.java

public static String editCompany(Connection conn, HttpServletRequest request, HttpServletResponse response)
        throws ServiceException {

    String status = "";
    DiskFileUpload fu = new DiskFileUpload();
    JSONObject j = new JSONObject();
    JSONObject j1 = new JSONObject();
    List fileItems = null;//from  w w  w  .ja va2 s  .  co  m
    FileItem fi1 = null;
    try {
        fileItems = fu.parseRequest(request);
    } catch (FileUploadException e) {
        throw ServiceException.FAILURE("SuperAdminHandler.editCompany", e);
    }

    HashMap arrParam = new HashMap();
    for (Iterator k = fileItems.iterator(); k.hasNext();) {
        fi1 = (FileItem) k.next();
        arrParam.put(fi1.getFieldName(), fi1.getString());
    }
    try {
        DbUtil.executeUpdate(conn,
                "update company set companyname=?, address=?, city=?, state=?, country=?, phone=?, fax=?, "
                        + "zip=?, timezone=?, website=? where companyid=?;",
                new Object[] { arrParam.get("companyname"), arrParam.get("address"), arrParam.get("city"),
                        arrParam.get("state"), arrParam.get("country"), arrParam.get("phone"),
                        arrParam.get("fax"), arrParam.get("zip"), arrParam.get("timezone"),
                        arrParam.get("website"), arrParam.get("companyid") });
        j.put("companyname", arrParam.get("companyname"));
        j.put("address", arrParam.get("address"));
        j.put("city", arrParam.get("city"));
        j.put("state", arrParam.get("state"));
        j.put("country", arrParam.get("country"));
        j.put("phone", arrParam.get("phone"));
        j.put("fax", arrParam.get("fax"));
        j.put("zip", arrParam.get("zip"));
        j.put("timezone", arrParam.get("timezone"));
        j.put("website", arrParam.get("website"));
        j.put("companyid", arrParam.get("companyid"));
        if (arrParam.get("image").toString().length() != 0) {
            genericFileUpload uploader = new genericFileUpload();
            try {
                uploader.doPost(fileItems, arrParam.get("companyid").toString(),
                        StorageHandler.GetProfileImgStorePath());
            } catch (ConfigurationException e) {
                throw ServiceException.FAILURE("SuperAdminHandler.createCompany", e);
            }
            if (uploader.isUploaded()) {
                DbUtil.executeUpdate(conn, "update company set image=? where companyid = ?",
                        new Object[] { ProfileImageServlet.ImgBasePath + arrParam.get("companyid").toString()
                                + uploader.getExt(), arrParam.get("companyid") });
                j.put("image", arrParam.get("companyid") + uploader.getExt());
            }
        }
        j1.append("data", j);
        status = j1.toString();
    } catch (JSONException e) {
        status = "failure";
        throw ServiceException.FAILURE("SuperAdminHandler.editCompany", e);
    }
    return status;
}

From source file:com.acciente.commons.htmlform.Parser.java

private static Object convertData(FileItem oFileItem, String sDataType)
        throws ParserException, UnsupportedEncodingException {
    Object oData;//from   w w  w . jav  a  2 s  .  c o  m

    if (Symbols.TOKEN_VARTYPE_STRING.equals(sDataType)) {
        oData = oFileItem.getString();
    } else if (Symbols.TOKEN_VARTYPE_INT.equals(sDataType)) {
        oData = new Integer(oFileItem.getString());
    } else if (Symbols.TOKEN_VARTYPE_FLOAT.equals(sDataType)) {
        oData = new Float(oFileItem.getString());
    } else if (Symbols.TOKEN_VARTYPE_BOOLEAN.equals(sDataType)) {
        oData = Boolean.valueOf(oFileItem.getString());
    } else if (Symbols.TOKEN_VARTYPE_FILE.equals(sDataType)) {
        oData = new FileHandle(oFileItem);
    } else {
        throw new ParserException("Internal error, unrecognized parameter type: " + sDataType);
    }

    return oData;
}

From source file:edu.stanford.epad.epadws.handlers.HandlerUtil.java

public static Map<String, Object> parsePostedData(String uploadDirPath, HttpServletRequest httpRequest,
        PrintWriter responseStream) throws Exception {
    File uploadDir = new File(uploadDirPath);
    if (!uploadDir.exists())
        uploadDir.mkdirs();/*from  w w  w  .j  a v  a2  s.  co m*/

    Map<String, Object> params = new HashMap<String, Object>();
    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<FileItem> items = upload.parseRequest(httpRequest);
    Iterator<FileItem> fileItemIterator = items.iterator();
    int fileCount = 0;
    while (fileItemIterator.hasNext()) {
        FileItem fileItem = fileItemIterator.next();
        if (fileItem.isFormField()) {
            if (params.get(fileItem.getFieldName()) == null)
                params.put(fileItem.getFieldName(), fileItem.getString());
            List values = (List) params.get(fileItem.getFieldName() + "_List");
            if (values == null) {
                values = new ArrayList();
                params.put(fileItem.getFieldName() + "_List", values);
            }
            values.add(fileItem.getString());
        } else {
            fileCount++;
            String fieldName = fileItem.getFieldName();
            if (fieldName.trim().length() == 0)
                fieldName = "File" + fileCount;
            String fileName = fileItem.getName();
            log.debug("Uploading file number " + fileCount);
            log.debug("FieldName: " + fieldName);
            log.debug("File Name: " + fileName);
            log.debug("ContentType: " + fileItem.getContentType());
            log.debug("Size (Bytes): " + fileItem.getSize());
            if (fileItem.getSize() != 0) {
                try {
                    String tempFileName = "temp" + System.currentTimeMillis() + "-" + fileName;
                    File file = new File(uploadDirPath + "/" + tempFileName);
                    log.debug("FileName: " + file.getAbsolutePath());
                    // write the file
                    fileItem.write(file);
                    if (params.get(fileItem.getFieldName()) == null)
                        params.put(fileItem.getFieldName(), file);
                    else
                        params.put(fileItem.getFieldName() + fileCount, file);
                    List values = (List) params.get(fileItem.getFieldName() + "_List");
                    if (values == null) {
                        values = new ArrayList();
                        params.put(fileItem.getFieldName() + "_List", values);
                    }
                    values.add(file);
                } catch (Exception e) {
                    e.printStackTrace();
                    log.warning("Error receiving file:" + e);
                    responseStream.print("error reading (" + fileCount + "): " + fileItem.getName());
                    continue;
                }
            }
        }
    }
    return params;
}

From source file:hudson.util.MultipartFormDataParser.java

public String get(String key) {
    FileItem fi = byName.get(key);
    if (fi == null)
        return null;
    return fi.getString();
}

From source file:azkaban.web.MultipartParser.java

@SuppressWarnings("unchecked")
public Map<String, Object> parseMultipart(HttpServletRequest request) throws IOException, ServletException {
    ServletFileUpload upload = new ServletFileUpload(_uploadItemFactory);
    List<FileItem> items = null;
    try {/*  w ww .j a  va  2  s  .  c  o m*/
        items = upload.parseRequest(request);
    } catch (FileUploadException e) {
        throw new ServletException(e);
    }

    Map<String, Object> params = new HashMap<String, Object>();
    for (FileItem item : items) {
        if (item.isFormField())
            params.put(item.getFieldName(), item.getString());
        else
            params.put(item.getFieldName(), item);
    }
    return params;
}