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:net.ontopia.topicmaps.classify.ClassifyUtils.java

public static ClassifiableContentIF getFileUploadContent(HttpServletRequest request) {
    // Handle file upload
    String contentType = request.getHeader("content-type");
    // out.write("CT: " + contentType + " " + tm + " " + id);
    if (contentType != null && contentType.startsWith("multipart/form-data")) {
        try {/*from  www . ja va 2s . c om*/
            FileUpload upload = new FileUpload(new DefaultFileItemFactory());
            for (FileItem item : upload.parseRequest(request)) {
                if (item.getSize() > 0) {
                    // ISSUE: could make use of content type if known
                    byte[] content = item.get();
                    ClassifiableContent cc = new ClassifiableContent();
                    String name = item.getName();
                    if (name != null)
                        cc.setIdentifier("fileupload:name:" + name);
                    else
                        cc.setIdentifier("fileupload:field:" + item.getFieldName());
                    cc.setContent(content);
                    return cc;
                }
            }
        } catch (Exception e) {
            throw new OntopiaRuntimeException(e);
        }
    }
    return null;
}

From source file:com.threecrickets.prudence.internal.lazy.LazyInitializationFile.java

/**
 * Creates a PHP-style item in the $_FILE map.
 * //  www .ja va2s.  co m
 * @param fileItem
 *        The file itme
 * @return A PHP-style $_FILE item
 */
private static Map<String, Object> createFileItemMap(FileItem fileItem) {
    Map<String, Object> exposedFileItem = new HashMap<String, Object>();
    exposedFileItem.put("name", fileItem.getName());
    exposedFileItem.put("type", fileItem.getContentType());
    exposedFileItem.put("size", fileItem.getSize());
    if (fileItem instanceof DiskFileItem) {
        DiskFileItem diskFileItem = (DiskFileItem) fileItem;
        exposedFileItem.put("tmp_name", diskFileItem.getStoreLocation().getAbsolutePath());
    }
    // exposedFileItem.put("error", );
    return exposedFileItem;
}

From source file:fr.paris.lutece.plugins.directory.utils.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./*from  ww  w  . j  av  a  2 s . 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) {
            json.accumulate(JSON_KEY_UPLOADED_FILES, fileItem.getName());
            json.accumulate(JSON_KEY_UPLOADED_FILES_SIZE, fileItem.getSize());
        }

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

    return json;
}

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//w  w  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:com.finedo.base.utils.upload.FileUploadUtils.java

public static final List<FileInfo> saveLicense(String uploadDir, List<FileItem> list) {

    List<FileInfo> filelist = new ArrayList<FileInfo>();

    if (list == null) {
        return filelist;
    }//from w ww  . j av  a 2 s .co  m

    //?
    //??
    logger.info("saveFiles uploadDir=============" + uploadDir);
    File dir = new File(uploadDir);
    if (!dir.isDirectory()) {
        dir.mkdirs();
    } else {

    }

    String uploadPath = uploadDir;

    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("utf-8");
    Iterator<FileItem> it = list.iterator();
    String name = "";
    String extName = "";

    while (it.hasNext()) {
        FileItem item = it.next();
        if (!item.isFormField()) {
            name = item.getName();
            if (name == null || name.trim().equals("")) {
                continue;
            }
            long l = item.getSize();
            logger.info("file size=" + l);
            if (10 * 1024 * 1024 < l) {
                logger.info("File size is greater than 10M!");
                continue;
            }
            name = name.replace("\\", "/");
            if (name.lastIndexOf("/") >= 0) {
                name = name.substring(name.lastIndexOf("/"));
            }
            logger.info("saveFiles name=============" + name);
            File saveFile = new File(uploadPath + name);
            try {
                item.write(saveFile);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {

            }

            String fileName = item.getName().replace("\\", "/");

            String[] ss = fileName.split("/");
            fileName = trimExtension(ss[ss.length - 1]);
            FileInfo fileinfo = new FileInfo();
            fileinfo.setName(fileName);
            fileinfo.setUname(name);
            fileinfo.setFilePath(uploadDir);
            fileinfo.setFileExt(extName);
            fileinfo.setSize(String.valueOf(item.getSize()));
            fileinfo.setContentType(item.getContentType());
            fileinfo.setFieldname(item.getFieldName());
            filelist.add(fileinfo);
        }
    }
    return filelist;
}

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

/**
 * @param modelManager//  ww w. 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:de.suse.swamp.modules.actions.DatapackActions.java

public static boolean storeFile(Databit dbit, boolean overwrite, FileItem fi, String uname) throws Exception {
    // skip empty uploads: 
    if (fi != null && !fi.getName().trim().equals("") && fi.getSize() > 0) {
        String fileDir = new SWAMPAPI().doGetProperty("ATTACHMENT_DIR", uname);

        if (!(new File(fileDir)).canWrite()) {
            throw new Exception("Cannot write to configured path: " + fileDir);
        }/*from  w  ww. j  av  a 2  s. c  o  m*/

        String fileName = fi.getName();
        // fix for browsers setting complete path as name: 
        if (fileName.indexOf("/") >= 0)
            fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
        if (fileName.indexOf("\\") >= 0)
            fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);

        File file = new File(fileDir + fs + dbit.getId() + "-" + fileName);
        if (!overwrite) {
            if (!file.createNewFile()) {
                throw new Exception("Cannot write to file: " + file.getName() + ". File already exists?");
            }
        } else {
            if (file.exists()) {
                file.delete();
            }
            // if its a file with a new name, delete the old one: 
            File oldFile = new File(fileDir + fs + dbit.getId() + "-" + dbit.getValue());
            if (oldFile.exists()) {
                Logger.DEBUG("Deleting old file: " + oldFile.getPath());
                oldFile.delete();
            }
        }

        FileOutputStream stream = new FileOutputStream(file);
        stream.write(fi.get());
        stream.close();
        return true;
    } else {
        return false;
    }
}

From source file:com.zving.platform.SysInfo.java

public static void uploadDB(HttpServletRequest request, HttpServletResponse response) {
    try {/*from w w  w . j  av  a 2  s . c om*/
        DiskFileItemFactory fileFactory = new DiskFileItemFactory();
        ServletFileUpload fu = new ServletFileUpload(fileFactory);
        List fileItems = fu.parseRequest(request);
        fu.setHeaderEncoding("UTF-8");
        Iterator iter = fileItems.iterator();

        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (!(item.isFormField())) {
                String OldFileName = item.getName();
                System.out.println("Upload DB FileName:" + OldFileName);
                long size = item.getSize();
                if ((((OldFileName == null) || (OldFileName.equals("")))) && (size == 0L)) {
                    continue;
                }
                OldFileName = OldFileName.substring(OldFileName.lastIndexOf("\\") + 1);
                String ext = OldFileName.substring(OldFileName.lastIndexOf("."));
                if (!(ext.toLowerCase().equals(".dat"))) {
                    response.sendRedirect("DBUpload.jsp?Error=?dat?");
                    return;
                }
                final String FileName = Config.getContextRealPath() + "WEB-INF/data/backup/DBUpload_"
                        + DateUtil.getCurrentDate("yyyyMMddHHmmss") + ".dat";
                item.write(new File(FileName));

                LongTimeTask ltt = LongTimeTask.getInstanceByType("Install");
                if (ltt != null) {
                    response.sendRedirect("DBUpload.jsp?Error=??");
                    return;
                }
                SessionListener.forceExit();
                Config.isAllowLogin = false;

                ltt = new LongTimeTask() {
                    public void execute() {
                        DBImport di = new DBImport();
                        di.setTask(this);
                        di.importDB(FileName, "Default");
                        setPercent(100);
                        Config.loadConfig();
                        CronManager.getInstance().init();
                    }
                };
                ltt.setType("Install");
                ltt.setUser(User.getCurrent());
                ltt.start();
                response.sendRedirect("DBUpload.jsp?TaskID=" + ltt.getTaskID());
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        Config.isAllowLogin = true;
    }
}

From source file:com.liferay.apio.architect.internal.body.MultipartToBodyConverter.java

private static void _storeFileItem(FileItem fileItem, Consumer<String> valueConsumer,
        Consumer<BinaryFile> fileConsumer) {

    try {//from w ww . j  av  a 2s.  co  m
        if (fileItem.isFormField()) {
            InputStream stream = fileItem.getInputStream();

            valueConsumer.accept(Streams.asString(stream));
        } else {
            BinaryFile binaryFile = new BinaryFile(fileItem.getInputStream(), fileItem.getSize(),
                    fileItem.getContentType(), fileItem.getName());

            fileConsumer.accept(binaryFile);
        }
    } catch (IOException ioe) {
        throw new BadRequestException("Invalid body", ioe);
    }
}

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

/**
 * ????,/*  w  w w . ja  va  2  s.co m*/
 * 
 * @param file
 *            FileItem
 * @return ?true?false
 */
private static boolean checkFile(FileItem file) {
    boolean bool = true;
    // ?
    if (file.getSize() > maxSize) {
        //LOGGER.error("=============>" + file.getFieldName() + "??");
        bool = false;
    }
    String fileName = file.getName();
    // ??
    String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
    if (!Arrays.<String>asList(extMap.get(IMAGE).split(",")).contains(fileExt)) {
        //LOGGER.error("" + file.getFieldName() + "??????\n??" + extMap.get(IMAGE) + "?");
        bool = false;
    }
    return bool;
}