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

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

Introduction

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

Prototype

long getSize();

Source Link

Document

Returns the size of the file item.

Usage

From source file:fr.paris.lutece.plugins.asynchronousupload.util.JSONUtils.java

/**
 * Builds a json object for the file item list.
 * Key is {@link #JSON_KEY_UPLOADED_FILES}, value is the array of uploaded
 * file./*www  .ja  v  a  2s  .  c o  m*/
 * @param listFileItem the fileItem list
 * @return the json
 */
public static JSONObject getUploadedFileJSON(List<FileItem> listFileItem) {
    JSONObject json = new JSONObject();

    if (listFileItem != null) {
        for (FileItem fileItem : listFileItem) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.element(JSON_KEY_FILE_NAME, fileItem.getName());
            try {

                jsonObject.element(JSON_KEY_FILE_PREVIEW, getPreviewImage(fileItem));

            } catch (IOException e) {

                AppLogService.error(e);
            }
            jsonObject.element(JSON_KEY_FILE_SIZE, fileItem.getSize());
            json.accumulate(JSON_KEY_UPLOADED_FILES, jsonObject);
        }

        json.element(JSON_KEY_FILE_COUNT, listFileItem.size());
    } else {
        // no file
        json.element(JSON_KEY_FILE_COUNT, 0);
    }

    return json;
}

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  w  ww .  j a  v a2s.  c o  m
                }
                break;
            }
        }
    }
    return false;
}

From source file:it.eng.spagobi.commons.utilities.PortletUtilities.java

/**
 * Gets the first uploaded file from a portlet request. This method creates a new file upload handler, 
 * parses the request, processes the uploaded items and then returns the first file as an
 * <code>UploadedFile</code> object.
 * @param portletRequest The input portlet request
 * @return   The first uploaded file object.
 *//*from w w w  .  jav a 2  s  .  c  o m*/
public static UploadedFile getFirstUploadedFile(PortletRequest portletRequest) {
    UploadedFile uploadedFile = null;
    try {

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

        //       Parse the request
        List /* FileItem */ items = upload.parseRequest((ActionRequest) portletRequest);

        //       Process the uploaded items
        Iterator iter = items.iterator();
        boolean endLoop = false;
        while (iter.hasNext() && !endLoop) {
            FileItem item = (FileItem) iter.next();

            if (item.isFormField()) {
                //serviceRequest.setAttribute(item.getFieldName(), item.getString());
            } else {
                uploadedFile = new UploadedFile();
                uploadedFile.setFileContent(item.get());
                uploadedFile.setFieldNameInForm(item.getFieldName());
                uploadedFile.setSizeInBytes(item.getSize());
                uploadedFile.setFileName(item.getName());

                endLoop = true;
            }
        }
    } catch (Exception e) {
        logger.error("Cannot parse multipart request", e);
    }
    return uploadedFile;

}

From source file:com.ylife.goods.model.UploadUtil.java

/**
 * Kindeditor/*from www.  j a v  a  2 s. c o  m*/
 * 
 * @param item
 *            FileItem
 * @param request
 *            HttpServletRequest
 * @return ?
 */
public static synchronized String uploadFileOneByFile(FileItem item, HttpServletRequest request) {
    String resoult = "";
    UpyunConf upConf = sysHelperMapper.selectUpyunConf();
    FastDFSInfo fastdfs = fastDFSService.getFastDFSInfoByCurr();
    if (item != null && item.getSize() != 0) {
        // ???
        if (!checkFile(item)) {
            throw new RuntimeException("???");
        }
        // ???
        if (upConf != null && "1".equals(upConf.getUsedStatus())) {
            // ???
            if (null == fastdfs || "0".equals(fastdfs.getUserd())) {
                resoult = uploadImgUpyun.uploadForRichEdit(item, upConf);
            } else {
                // FastDFS
                resoult = uploadImgUpyun.uploadForRichEdit(item, upConf);
                resoult = uploadImgFastDFS.saveToFastDFS(resoult, fastdfs);
            }
        } else {
            // Java?
            // ??
            if (null == fastdfs || "0".equals(fastdfs.getUserd())) {
                resoult = uploadImgJava.uploadForRichEdit(item);
            } else {
                // FastDFS
                resoult = uploadImgJava.uploadForRichEditSaveFastDFS(item);
                resoult = uploadImgFastDFS.saveToFastDFS(resoult, fastdfs);
            }
        }
        return resoult;
    } else {
        return null;
    }
}

From source file:com.ylife.goods.model.UploadUtil.java

/**
 * Kindeditor/*w w  w.ja v  a  2  s . com*/
 * 
 * @param item
 *            FileItem
 * @param request
 *            HttpServletRequest
 * @return ?
 */
public static synchronized String uploadFileOneByFileSite(FileItem item, HttpServletRequest request) {
    String resoult = "";
    UpyunConf upConf = sysHelperMapper.selectUpyunConf();
    FastDFSInfo fastdfs = fastDFSService.getFastDFSInfoByCurr();
    if (item != null && item.getSize() != 0) {
        // ???
        if (!checkFile(item)) {
            throw new RuntimeException("???");
        }
        // ???
        if (upConf != null && "1".equals(upConf.getUsedStatus())) {
            // ???
            if (null == fastdfs || "0".equals(fastdfs.getUserd())) {
                resoult = uploadImgUpyun.uploadForRichEdit(item, upConf);
            } else {
                // FastDFS
                resoult = uploadImgUpyun.uploadForRichEdit(item, upConf);
                resoult = uploadImgFastDFS.saveToFastDFS(resoult, fastdfs);
            }
        } else {
            // Java?
            // ??
            if (null == fastdfs || "0".equals(fastdfs.getUserd())) {
                resoult = uploadImgJava.uploadForRichEdit(item);
            } else {
                // FastDFS
                resoult = uploadImgJava.uploadForRichEditSaveFastDFS(item);
                resoult = uploadImgFastDFS.saveToFastDFS(resoult, fastdfs);
            }
        }
        return resoult;
    } else {
        return null;
    }
}

From source file:fr.paris.lutece.portal.service.user.attribute.AdminUserFieldService.java

/**
 * Check if the user fields are correctly filled
 * @param request HttpServletRequest//from  w w  w  .j  av a2  s.  c  o m
 * @param locale locale
 * @return null if there are no problem
 */
public static String checkUserFields(HttpServletRequest request, Locale locale) {
    // Specific attributes
    List<IAttribute> listAttributes = _attributeService.getAllAttributesWithoutFields(locale);

    for (IAttribute attribute : listAttributes) {
        if (attribute.isAttributeImage()) {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            FileItem fileItem = multipartRequest
                    .getFile(PARAMETER_ATTRIBUTE + CONSTANT_UNDERSCORE + attribute.getIdAttribute());
            String strUpdateAttribute = request.getParameter(
                    PARAMETER_UPDATE_ATTRIBUTE + CONSTANT_UNDERSCORE + attribute.getIdAttribute());

            if (attribute.isMandatory() && (strUpdateAttribute != null)
                    && ((fileItem == null) || (fileItem.getSize() == 0))) {
                return AdminMessageService.getMessageUrl(request, Messages.MANDATORY_FIELDS,
                        AdminMessage.TYPE_STOP);
            }
        } else {
            String value = request
                    .getParameter(PARAMETER_ATTRIBUTE + CONSTANT_UNDERSCORE + attribute.getIdAttribute());

            if (attribute.isMandatory() && ((value == null) || value.equals(CONSTANT_EMPTY_STRING))) {
                return AdminMessageService.getMessageUrl(request, Messages.MANDATORY_FIELDS,
                        AdminMessage.TYPE_STOP);
            }
        }
    }

    return null;
}

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

public static void parseRequest(HttpServletRequest request, HashMap<String, String> arrParam,
        ArrayList<FileItem> fi, boolean fileUpload) throws ServiceException {
    DiskFileUpload fu = new DiskFileUpload();
    FileItem fi1 = null;
    List fileItems = null;//w w w .j  av a2  s .  com
    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();
        if (fi1.isFormField()) {
            arrParam.put(fi1.getFieldName(), fi1.getString());
        } else {
            try {
                String fileName = new String(fi1.getName().getBytes(), "UTF8");
                if (fi1.getSize() != 0) {
                    fi.add(fi1);
                    fileUpload = true;
                }
            } catch (UnsupportedEncodingException ex) {
            }
        }
    }
}

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 {//  w  w w. j a  v a2s. c om
        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;/*from  w w  w  . ja va 2 s. 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.news.util.UploadFileUtil.java

public static String upload(HttpServletRequest request, String paramName, String fileName) {
    String result = "";
    File file;//  w  w w . j  ava2 s  .  c  om
    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;
}