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: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;//from  ww  w .  j  a  v  a2s  .  c o  m
    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:com.stratelia.webactiv.quizz.QuestionHelper.java

protected static void addImageToAnswer(Answer answer, FileItem item, QuestionForm form, String componentId,
        String subdir) throws IOException {
    // it's a file part
    if (QuestionHelper.isCorrectFile(item)) {
        // the part actually contained a file
        String logicalName = FileUploadUtil.getFileName(item);
        String type = logicalName.substring(logicalName.indexOf('.') + 1, logicalName.length());
        String physicalName = Long.toString(new Date().getTime()) + form.getAttachmentSuffix() + "." + type;
        form.setAttachmentSuffix(form.getAttachmentSuffix() + 1);
        File dir = new File(
                FileRepositoryManager.getAbsolutePath(componentId) + subdir + File.separator + physicalName);
        long size = item.getSize();
        FileUploadUtil.saveToFile(dir, item);
        if (size > 0) {
            answer.setImage(physicalName);
            form.setFile(true);// ww w  . j a va2s.  c  om
        }
    }
}

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;/*  w  ww. j a  va2s . 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.xpn.xwiki.web.Utils.java

/**
 * Get the content of an uploaded file, corresponding to the specified form field.
 * /*from w w  w .  j  av a2  s . c  o  m*/
 * @param filelist the list of uploaded files, computed by the FileUpload plugin
 * @param name the name of the form field
 * @return the content of the file, if the specified field name does correspond to an uploaded file, or {@code null}
 *         otherwise
 * @throws XWikiException if the file cannot be read due to an underlying I/O exception
 */
public static byte[] getContent(List<FileItem> filelist, String name) throws XWikiException {
    for (FileItem item : filelist) {
        if (name.equals(item.getFieldName())) {
            byte[] data = new byte[(int) item.getSize()];
            InputStream fileis = null;
            try {
                fileis = item.getInputStream();
                fileis.read(data);
            } catch (IOException e) {
                throw new XWikiException(XWikiException.MODULE_XWIKI_APP,
                        XWikiException.ERROR_XWIKI_APP_UPLOAD_FILE_EXCEPTION,
                        "Exception while reading uploaded parsed file", e);
            } finally {
                IOUtils.closeQuietly(fileis);
            }

            return data;
        }
    }

    return null;
}

From source file:com.zving.cms.site.Site.java

public static void uploadSite(HttpServletRequest request, HttpServletResponse response) {
    try {//from   w  w w  .  j  a v a2 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();
                LogUtil.info("Upload Site 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("SiteImportStep1.jsp?Error=1");
                    return;
                }
                String FileName = "SiteUpload_" + DateUtil.getCurrentDate("yyyyMMddHHmmss") + ".dat";
                String Path = Config.getContextRealPath() + "WEB-INF/data/backup/";
                item.write(new File(Path + FileName));
                response.sendRedirect("SiteImportStep2.jsp?FileName=" + FileName);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.aaasec.sigserv.csspserver.utility.SpServerLogic.java

public static String processFileUpload(HttpServletRequest request, HttpServletResponse response,
        RequestModel req) {//from   w  ww  .  ja  v  a2  s.  c  o m
    // Create a factory for disk-based file items
    Map<String, String> paraMap = new HashMap<String, String>();
    File uploadedFile = null;
    boolean uploaded = false;
    DiskFileItemFactory factory = new DiskFileItemFactory();
    String uploadDirName = FileOps.getfileNameString(SpModel.getDataDir(), "uploads");
    FileOps.createDir(uploadDirName);
    File storageDir = new File(uploadDirName);
    factory.setRepository(storageDir);

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    try {
        // Parse the request
        List<FileItem> items = upload.parseRequest(request);
        for (FileItem item : items) {
            if (item.isFormField()) {
                String name = item.getFieldName();
                String value = item.getString();
                paraMap.put(name, value);
            } else {
                String fieldName = item.getFieldName();
                String fileName = item.getName();
                if (fileName.length() > 0) {
                    String contentType = item.getContentType();
                    boolean isInMemory = item.isInMemory();
                    long sizeInBytes = item.getSize();
                    uploadedFile = new File(storageDir, fileName);
                    try {
                        item.write(uploadedFile);
                        uploaded = true;
                    } catch (Exception ex) {
                        LOG.log(Level.SEVERE, null, ex);
                    }
                }
            }

        }
        if (uploaded) {
            return SpServerLogic.getDocUploadResponse(req, uploadedFile);
        } else {
            if (paraMap.containsKey("xmlName")) {
                return SpServerLogic.getServerDocResponse(req, paraMap.get("xmlName"));
            }
        }
    } catch (FileUploadException ex) {
        LOG.log(Level.SEVERE, null, ex);
    }
    response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    return "";
}

From source file:com.krawler.esp.portalmsg.forummsgcomm.java

public static void doPost(Connection conn, java.util.List fileItems, String postid,
        java.sql.Timestamp docdatemod, String userid, String sendefolderpostid) throws ServiceException {
    try {//from w ww  .j  a  va2s . c  o m
        String destinationDirectory = StorageHandler.GetDocStorePath() + StorageHandler.GetFileSeparator()
                + "attachment";
        java.io.File destDir = new java.io.File(destinationDirectory);
        String Ext = "";
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
        String fileid;
        long size;
        org.apache.commons.fileupload.DiskFileUpload fu = new org.apache.commons.fileupload.DiskFileUpload();
        fu.setSizeMax(-1);
        fu.setSizeThreshold(4096);
        fu.setRepositoryPath(destinationDirectory);
        for (java.util.Iterator i = fileItems.iterator(); i.hasNext();) {
            org.apache.commons.fileupload.FileItem fi = (org.apache.commons.fileupload.FileItem) i.next();
            if (!fi.isFormField()) {
                String fileName = null;
                fileid = UUID.randomUUID().toString();
                try {
                    fileName = getFileName(fi);
                    //                        fileName = new String(fi.getName().getBytes(), "UTF8");
                    if (fileName.contains(".")) {
                        Ext = fileName.substring(fileName.lastIndexOf("."));
                    }
                    size = fi.getSize();
                    if (size != 0) {

                        File uploadFile = new File(destinationDirectory + "/" + fileid + Ext);
                        fi.write(uploadFile);
                        fildoc(conn, fileid, fileName, docdatemod, postid, fileid + Ext, userid, size,
                                sendefolderpostid);
                    }

                } catch (Exception e) {
                    throw ServiceException.FAILURE("ProfileHandler.updateProfile", e);
                }
            }
        }
    } catch (ConfigurationException ex) {
        Logger.getLogger(forummsgcomm.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:fr.paris.lutece.portal.web.xsl.XslExportJspBean.java

/**
 * Get a file contained in the request from the name of the parameter
 *
 * @param strFileInputName name of the file parameter of the request
 * @param request the request//from ww  w  . ja v  a  2s.  co m
 * @return file the file contained in the request with the given parameter key
 */
private static File getFileData(String strFileInputName, HttpServletRequest request) {
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    FileItem fileItem = multipartRequest.getFile(strFileInputName);

    if ((fileItem != null) && (fileItem.getName() != null) && !EMPTY_STRING.equals(fileItem.getName())) {
        File file = new File();
        PhysicalFile physicalFile = new PhysicalFile();
        physicalFile.setValue(fileItem.get());
        file.setTitle(FileUploadService.getFileNameOnly(fileItem));
        file.setSize((int) fileItem.getSize());
        file.setPhysicalFile(physicalFile);
        file.setMimeType(FileSystemUtil.getMIMEType(FileUploadService.getFileNameOnly(fileItem)));

        return file;
    }

    return null;
}

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);//from  w w w  .  j  a v  a2  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.qwazr.server.StreamFileUploadTest.java

@Test
public void extract() throws IOException, FileUploadException {
    final InputStream input = StreamFileUploadTest.class.getResourceAsStream(MULTIPART_TEST);
    final File tmpDirectory = Files.createTempDirectory(StreamFileUploadTest.class.getName()).toFile();
    final StreamFileUpload parser = new StreamFileUpload(tmpDirectory);
    final List<FileItem> files = parser.parse(MIME_TYPE, -1, "UTF-8", input);
    Assert.assertNotNull(files);/*  ww  w  . j av a 2 s  .  co m*/
    Assert.assertEquals(2, files.size());
    for (FileItem fileItem : files)
        Assert.assertEquals(fileItem.getSize(),
                IOUtils.skip(fileItem.getInputStream(), fileItem.getSize() + 1));
}