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: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 va  2 s. co  m*/

    // 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:com.w4t.webfileuploadkit.WebFileUploadRenderer.java

public void readData(final WebComponent component) {
    HttpServletRequest request = ContextProvider.getRequest();
    String fileName = request.getParameter(component.getUniqueID());
    // don't ask for fileName == null; in this case there is actually an upload
    if (!"".equals(fileName)) {
        IFileUploadRequest uploadRequest = (IFileUploadRequest) request;
        WebFileUpload upload = (WebFileUpload) component;
        FileItem uploadedFile = uploadRequest.getFileItem(upload.getUniqueID());
        if (uploadedFile.getSize() != 0) {
            IFileUploadAdapter adapter = (IFileUploadAdapter) upload.getAdapter(IFileUploadAdapter.class);
            adapter.setFileItem(uploadedFile);

            int id = WebFileUploadEvent.FILEUPLOADED;
            WebFileUploadEvent evt = new WebFileUploadEvent(upload, id);
            EventQueue.getEventQueue().addToQueue(evt);
        }/*from   w  w w .j  a v  a2s .  c  om*/
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.search.controller.UpdateUrisInIndex.java

/**
 * Web service for update in search index of a list of URIs.
 * //from  w  ww .j a  v a2s .c  o m
 * @throws IOException
 */
protected int doUpdateUris(HttpServletRequest req, SearchIndexer indexer) throws ServletException, IOException {
    Map<String, List<FileItem>> map = new VitroRequest(req).getFiles();
    if (map == null) {
        throw new ServletException("Expected Multipart Content");
    }

    Charset enc = getEncoding(req);

    int uriCount = 0;
    for (String name : map.keySet()) {
        for (FileItem item : map.get(name)) {
            log.debug("Found " + item.getSize() + " byte file for '" + name + "'");
            uriCount += processFileItem(indexer, item, enc);
        }
    }
    return uriCount;
}

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

public static HrmsDocs uploadFile(Session session, FileItem fi, ConfigRecruitmentData ConfigRecruitmentDataobj,
        HashMap arrparam, boolean flag)
        throws ServiceException, SessionExpiredException, UnsupportedEncodingException {
    HrmsDocs docObj = new HrmsDocs();
    User userObj = null;//w  w  w.  ja  v  a 2s. co m
    Jobapplicant jobapp = null;
    try {
        String fileName = new String(fi.getName().getBytes(), "UTF8");
        String Ext = "";
        if (fileName.contains(".")) {
            Ext = fileName.substring(fileName.lastIndexOf("."));
        }
        docObj.setDocname(fileName);
        docObj.setReferenceid(ConfigRecruitmentDataobj.getId());
        docObj.setStorename("");
        docObj.setDoctype("");
        docObj.setUploadedon(new Date());
        docObj.setUploadedby(ConfigRecruitmentDataobj.getCol1() + " " + ConfigRecruitmentDataobj.getCol2());
        docObj.setStorageindex(1);
        docObj.setDocsize(fi.getSize() + "");
        docObj.setDeleted(false);
        if (!StringUtil.isNullOrEmpty((String) arrparam.get("docname"))) {
            docObj.setDispdocname((String) arrparam.get("docname"));
        }
        if (!StringUtil.isNullOrEmpty((String) arrparam.get("docdesc"))) {
            docObj.setDocdesc((String) arrparam.get("docdesc"));
        }
        session.save(docObj);
        String fileid = docObj.getDocid();
        if (Ext.length() > 0) {
            fileid = fileid + Ext;
        }
        docObj.setStorename(fileid);
        session.update(docObj);
        String temp = StorageHandler.GetDocStorePath1();
        uploadFile(fi, temp, fileid);

    } catch (ServiceException e) {
        throw ServiceException.FAILURE(e.getMessage(), e);
    }
    return docObj;
}

From source file:ilarkesto.form.UploadFormField.java

@Override
public void update(Map<String, String> data, Collection<FileItem> uploadedFiles) {
    maxFileSizeExceeded = false;/* w  ww  .j av  a  2  s .  c o m*/
    for (FileItem item : uploadedFiles) {
        if (item.getFieldName().equals(getName())) {
            if (item.getSize() == 0) {
                file = null;
                return;
            }
            if (maxFilesize != null && item.getSize() > maxFilesize) {
                maxFileSizeExceeded = true;
                return;
            }
            file = new File(applicationTempDir + "/" + folderIdGenerator.generateId() + "/" + item.getName());
            file.getParentFile().mkdirs();
            try {
                item.write(file);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    }
}

From source file:com.google.jenkins.plugins.credentials.oauth.JsonServiceAccountConfig.java

@DataBoundConstructor
public JsonServiceAccountConfig(FileItem jsonKeyFile, String prevJsonKeyFile) {
    if (jsonKeyFile != null && jsonKeyFile.getSize() > 0) {
        try {/*from  ww  w . j a v a 2 s .  c  om*/
            JsonKey jsonKey = JsonKey.load(new JacksonFactory(), jsonKeyFile.getInputStream());
            if (jsonKey.getClientEmail() != null && jsonKey.getPrivateKey() != null) {
                try {
                    this.jsonKeyFile = writeJsonKeyToFile(jsonKey);
                } catch (IOException e) {
                    LOGGER.log(Level.SEVERE, "Failed to write json key to file", e);
                }
            }
        } catch (IOException e) {
            LOGGER.log(Level.SEVERE, "Failed to read json key from file", e);
        }
    } else if (prevJsonKeyFile != null && !prevJsonKeyFile.isEmpty()) {
        this.jsonKeyFile = prevJsonKeyFile;
    }
}

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

public static File getfile(HttpServletRequest request, String docid) throws ConfigurationException {
    String destinationDirectory = StorageHandler.GetDocStorePath() + StorageHandler.GetFileSeparator()
            + "baseCamxml";
    java.io.File destDir = new java.io.File(destinationDirectory);

    if (!destDir.exists()) {
        destDir.mkdirs();/*from www .j a v  a  2  s  . c  o  m*/
    }
    DiskFileUpload fu = new DiskFileUpload();
    String Ext = null;
    File uploadFile = null;
    List fileItems = null;
    try {
        fileItems = fu.parseRequest(request);
    } catch (FileUploadException e) {
        KrawlerLog.op.warn("Problem While Uploading file :" + e.toString());
    }
    for (Iterator i = fileItems.iterator(); i.hasNext();) {
        FileItem fi = (FileItem) i.next();
        if (!fi.isFormField()) {
            String fileName = null;
            try {
                fileName = new String(fi.getName().getBytes(), "UTF8");
                if (fileName.contains(".")) {
                    Ext = fileName.substring(fileName.lastIndexOf("."));
                }
                if (fi.getSize() != 0) {
                    uploadFile = new File(
                            destinationDirectory + StorageHandler.GetFileSeparator() + docid + ".xml");
                    fi.write(uploadFile);
                }
            } catch (Exception e) {
                KrawlerLog.op.warn("Problem While Reading file :" + e.toString());
            }
        }
    }

    return uploadFile;
}

From source file:fll.web.schedule.UploadSchedule.java

@Override
protected void processRequest(final HttpServletRequest request, final HttpServletResponse response,
        final ServletContext application, final HttpSession session) throws IOException, ServletException {
    clearSesionVariables(session);//from   www .jav a2s. c  o m

    final File file = File.createTempFile("fll", null);
    file.deleteOnExit();
    try {
        // must be first to ensure the form parameters are set
        UploadProcessor.processUpload(request);

        // process file and keep track of filename in session.scheduleFilename
        final FileItem scheduleFileItem = (FileItem) request.getAttribute("scheduleFile");
        if (null == scheduleFileItem || scheduleFileItem.getSize() == 0) {
            session.setAttribute(SessionAttributes.MESSAGE,
                    "<p class='error'>A file containing a schedule must be specified</p>");
            WebUtils.sendRedirect(application, response, "/admin/index.jsp");
            return;
        } else {
            scheduleFileItem.write(file);
            session.setAttribute("uploadSchedule_file", file);

            WebUtils.sendRedirect(application, response, "/schedule/CheckScheduleExists");
            return;
        }
    } catch (final FileUploadException e) {
        LOGGER.error("There was an error processing the file upload", e);
        throw new FLLRuntimeException("There was an error processing the file upload", e);
    } catch (final Exception e) {
        final String message = "There was an error writing the uploaded file to the filesystem";
        LOGGER.error(message, e);
        throw new FLLRuntimeException(message, e);
    }

}

From source file:com.google.jenkins.plugins.credentials.oauth.P12ServiceAccountConfig.java

@DataBoundConstructor
public P12ServiceAccountConfig(String emailAddress, FileItem p12KeyFile, String prevP12KeyFile) {
    this.emailAddress = emailAddress;
    if (p12KeyFile != null && p12KeyFile.getSize() > 0) {
        try {//from  www  .ja  v a 2s  .  c  om
            this.p12KeyFile = writeP12KeyToFile(p12KeyFile);
        } catch (IOException e) {
            LOGGER.log(Level.SEVERE, "Failed to write json key to file", e);
        }
    } else if (prevP12KeyFile != null && !prevP12KeyFile.isEmpty()) {
        this.p12KeyFile = prevP12KeyFile;
    }
}

From source file:com.globalsight.everest.webapp.pagehandler.administration.config.xmldtd.FileUploader.java

private File saveTmpFile(List<FileItem> fileItems) throws Exception {

    File file = File.createTempFile("GSDTDUpload", null);

    // Set overall request size constraint
    long uploadTotalSize = 0;
    for (FileItem item : fileItems) {
        if (!item.isFormField()) {
            uploadTotalSize += item.getSize();
        }/*from   ww w  .  j  av  a 2  s  .co  m*/
    }

    for (ProcessStatus status : listeners) {
        status.setTotalSize(uploadTotalSize);
    }

    log.debug("File size: " + uploadTotalSize);

    for (FileItem item : fileItems) {
        if (!item.isFormField()) {
            item.write(file);
            setName(getFileName(item.getName()));
        } else {
            fields.put(item.getFieldName(), item.getString("utf-8"));
        }
    }

    for (ProcessStatus status : listeners) {
        status.finished();
    }

    return file;
}