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:com.skin.generator.action.UploadTestAction.java

/**
 * @throws IOException//from   www . j ava 2 s  . c om
 * @throws ServletException
 */
@UrlPattern("/upload/test1.html")
public void test1() throws IOException, ServletException {
    logger.info("method: " + this.request.getMethod() + " " + this.request.getRequestURI() + " "
            + this.request.getQueryString());
    String home = this.servletContext.getRealPath("/WEB-INF/tmp");
    Map<String, Object> result = new HashMap<String, Object>();
    RandomAccessFile raf = null;

    try {
        Map<String, Object> map = this.parse(this.request);
        FileItem fileItem = (FileItem) map.get("fileData");
        fileItem.write(new File(home, fileItem.getName()));
        result.put("status", 200);
        result.put("message", "??");
        result.put("start", fileItem.getSize());
        JsonUtil.callback(this.request, this.response, result);
        return;
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        result.put("status", 500);
        result.put("message", "?");
        JsonUtil.callback(this.request, this.response, result);
        return;
    } finally {
        close(raf);
    }
}

From source file:edu.gmu.csiss.automation.pacs.servlet.FileUploadServlet.java

private void processUploadFile(FileItem item, PrintWriter pw) throws Exception {
    String filename = item.getName();
    System.out.println(filename);
    int index = filename.lastIndexOf("\\");
    filename = filename.substring(index + 1, filename.length());

    long fileSize = item.getSize();

    if ("".equals(filename) && fileSize == 0) {
        throw new RuntimeException("You didn't upload a file.");
        //return;
    }// w  ww.jav a  2s.  c  om

    File uploadFile = new File(filePath + "/" + filename);
    item.write(uploadFile);
    pw.println("<a id=\"filelink\" href=\"" + prefix_url + filename + "\" >Link</a> to the uploaded file : "
            + filename);
    System.out.println(fileSize + "\r\n");
}

From source file:by.creepid.jsf.fileupload.UploadRenderer.java

/**
 * Decode any new state of this UIComponent from the request contained in
 * the specified FacesContext, and store this state as needed.
 *
 * During decoding, events may be enqueued for later processing (by event
 * listeners who have registered an interest), by calling queueEvent().
 *
 * @param context/*w w w .j a va  2  s .co  m*/
 */
@Override
public void decode(FacesContext context) {
    ExternalContext external = context.getExternalContext();
    HttpServletRequest request = (HttpServletRequest) external.getRequest();

    String clientId = getClientId(context);
    FileItem item = (FileItem) request.getAttribute(clientId);

    ValueExpression valueExpr = getValueExpression("value");
    if (valueExpr != null) {

        UIComponent component = getCurrentComponent(context);
        if (item.getSize() > 0) {
            String target = getAttributes().get("target").toString();

            String realPath = getServletRealPath(external, target);
            String fileName = item.getName();

            String longFileName = getLongFileName(realPath, fileName);
            String shortFileName = target + "/" + fileName;
            //if the target location ends with the forward slash,
            //just join the target and the filename
            if (target.endsWith("/")) {
                shortFileName = target + fileName;
            }

            ((EditableValueHolder) component)
                    .setSubmittedValue(new UploadedFile(item, longFileName, shortFileName));
        } else {
            ((EditableValueHolder) component).setSubmittedValue(new UploadedFile());
        }
        ((EditableValueHolder) component).setValid(true);
    }

    Object target = getAttributes().get("target");
    if (target != null) {

        String realPath = getServletRealPath(external, target.toString());
        File file = new File(getLongFileName(realPath, item.getName()));

        File parent = file.getParentFile();
        if (!parent.exists()) {
            parent.mkdirs();
        }

        try {
            if (item.getSize() > 0 && item.getName().length() > 0) {
                item.write(file);
            }
        } catch (Exception ex) {
            throw new FacesException(ex);
        }
    }
}

From source file:com.github.davidcarboni.encryptedfileupload.EncryptedFileItemSerializeTest.java

/**
 * Test creation of a field for which the amount of data falls above the
 * configured threshold./*from  w w w . j  ava  2 s .c om*/
 */
@Test
public void testAboveThreshold() throws Exception {
    // Create the FileItem
    byte[] testFieldValueBytes = createContentBytes(threshold + 1);
    FileItem item = createFileItem(testFieldValueBytes);

    // Check state is as expected
    assertFalse("Initial: in memory", item.isInMemory());
    assertEquals("Initial: size", item.getSize(), testFieldValueBytes.length);
    compareBytes("Initial", item.get(), testFieldValueBytes);

    // Serialize & Deserialize
    FileItem newItem = (FileItem) serializeDeserialize(item);

    // Test deserialized content is as expected
    assertFalse("Check in memory", newItem.isInMemory());
    compareBytes("Check", testFieldValueBytes, newItem.get());

    // Compare FileItem's (except byte[])
    compareFileItems(item, newItem);

    item.delete();
    newItem.delete();
}

From source file:com.Uploader.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new ServletException("Content type is not multipart/form-data");
    }//from   w ww .  ja v  a2  s .  c  o  m

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.write("<html><head></head><body>");
    try {
        List<FileItem> fileItemsList = uploader.parseRequest(request);
        Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
        while (fileItemsIterator.hasNext()) {
            FileItem fileItem = fileItemsIterator.next();
            System.out.println("FieldName=" + fileItem.getFieldName());
            System.out.println("FileName=" + fileItem.getName());
            System.out.println("ContentType=" + fileItem.getContentType());
            System.out.println("Size in bytes=" + fileItem.getSize());
            File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator
                    + fileItem.getName());
            System.out.println("Absolute Path at server=" + file.getAbsolutePath());
            fileItem.write(file);
            out.write("File " + fileItem.getName() + " uploaded successfully.");
            out.write("<br>");
            out.write("<a href=\"Uploader?fileName=" + fileItem.getName() + "\">Download " + fileItem.getName()
                    + "</a>");
        }
    } catch (FileUploadException e) {
        out.write("Exception in uploading file.");
        e.printStackTrace();
    } catch (Exception e) {
        out.write("Exception in uploading file.");
        e.printStackTrace();
    }
    out.write("</body></html>");
}

From source file:cpabe.controladores.UploadDownloadFileAdvancedServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new ServletException("Content type is not multipart/form-data");
    }//from  w  w w  .  j  a va  2s . c o  m

    // response.setContentType("text/html");
    //  PrintWriter out = response.getWriter();
    // out.write("<html><head></head><body>");
    try {
        List<FileItem> fileItemsList = uploader.parseRequest(request);
        Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
        while (fileItemsIterator.hasNext()) {
            FileItem fileItem = fileItemsIterator.next();

            System.out.println("FieldName=" + fileItem.getFieldName());
            System.out.println("FileName=" + fileItem.getName());
            System.out.println("ContentType=" + fileItem.getContentType());
            System.out.println("Size in bytes=" + fileItem.getSize());

            File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator
                    + fileItem.getName());
            //setar no objeto CaminhoArquivo os dados do arquivo anexado
            String caminho = file.getAbsolutePath();
            String nome = fileItem.getName();

            CaminhoArquivo c = new CaminhoArquivo();
            c.setNome(nome);
            c.setWay(caminho);

            request.setAttribute("caminho", c);
            System.out.println("caminho=" + caminho);
            System.out.println("nome=" + nome);

            System.out.println("Absolute Path at server=" + file.getAbsolutePath());
            fileItem.write(file);

            request.getRequestDispatcher("/avancado/encriptar/encriptar1.jsp").forward(request, response);

            // out.write("File " + fileItem.getName() + " uploaded successfully.");
            // out.write("<br>");
            // out.write("<a href=\"UploadDownloadFileServlet?fileName=" + fileItem.getName() + "\">Download " + fileItem.getName() + "</a>");
        }

    } catch (FileUploadException e) {
        //  out.write("Exception in uploading file.");
    } catch (Exception e) {
        //  out.write("Exception in uploading file.");
    }
    // out.write("</body></html>");
}

From source file:cpabe.controladores.UploadDownloadFileServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new ServletException("Content type is not multipart/form-data");
    }//from  w w w  .  j  a  v  a2  s  .com

    // response.setContentType("text/html");
    //  PrintWriter out = response.getWriter();
    // out.write("<html><head></head><body>");
    try {
        List<FileItem> fileItemsList = uploader.parseRequest(request);
        Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
        while (fileItemsIterator.hasNext()) {
            FileItem fileItem = fileItemsIterator.next();

            System.out.println("FieldName=" + fileItem.getFieldName());
            System.out.println("FileName=" + fileItem.getName());
            System.out.println("ContentType=" + fileItem.getContentType());
            System.out.println("Size in bytes=" + fileItem.getSize());

            File file = new File(request.getServletContext().getAttribute("FILES_DIR") + File.separator
                    + fileItem.getName());
            //setar no objeto CaminhoArquivo os dados do arquivo anexado
            String caminho = file.getAbsolutePath();
            String nome = fileItem.getName();

            CaminhoArquivo c = new CaminhoArquivo();
            c.setNome(nome);
            c.setWay(caminho);

            request.setAttribute("caminho", c);
            System.out.println("caminho=" + caminho);
            System.out.println("nome=" + nome);

            System.out.println("Absolute Path at server=" + file.getAbsolutePath());
            fileItem.write(file);

            request.getRequestDispatcher("/formularios/encriptar/encriptar1.jsp").forward(request, response);

            // out.write("File " + fileItem.getName() + " uploaded successfully.");
            // out.write("<br>");
            // out.write("<a href=\"UploadDownloadFileServlet?fileName=" + fileItem.getName() + "\">Download " + fileItem.getName() + "</a>");
        }

    } catch (FileUploadException e) {
        //  out.write("Exception in uploading file.");
    } catch (Exception e) {
        //  out.write("Exception in uploading file.");
    }
    // out.write("</body></html>");
}

From source file:com.krawler.spring.hrms.common.hrmsExtApplDocsDAOImpl.java

public void parseRequest(List fileItems, HashMap<String, String> arrParam, ArrayList<FileItem> fi,
        boolean fileUpload) throws ServiceException {

    FileItem fi1 = null;
    for (Iterator k = fileItems.iterator(); k.hasNext();) {
        fi1 = (FileItem) k.next();//from w ww. ja  v a  2 s. c  o  m
        if (fi1.isFormField()) {
            arrParam.put(fi1.getFieldName(), fi1.getString());
        } else {
            if (fi1.getSize() != 0) {
                fi.add(fi1);
                fileUpload = true;
            }
        }
    }
}

From source file:com.github.davidcarboni.encryptedfileupload.EncryptedFileItemSerializeTest.java

/**
 * Helper method to test creation of a field when a repository is used.
 *///from ww w  .  j  a v a  2s .c  o  m
public void testInMemoryObject(byte[] testFieldValueBytes, File repository) {
    FileItem item = createFileItem(testFieldValueBytes, repository);

    // Check state is as expected
    assertTrue("Initial: in memory", item.isInMemory());
    assertEquals("Initial: size", item.getSize(), testFieldValueBytes.length);
    compareBytes("Initial", item.get(), testFieldValueBytes);

    // Serialize & Deserialize
    FileItem newItem = (FileItem) serializeDeserialize(item);

    // Test deserialized content is as expected
    assertTrue("Check in memory", newItem.isInMemory());
    compareBytes("Check", testFieldValueBytes, newItem.get());

    // Compare FileItem's (except byte[])
    compareFileItems(item, newItem);
}

From source file:com.sun.licenseserver.License.java

/**
 * Construct a license object using the input provided in the 
 * request object,//from w w  w.ja  v a 2s .  com
 * 
 * @param req
 */
public License(HttpServletRequest req) {
    if (FileUpload.isMultipartContent(req)) {
        DiskFileUpload upload = new DiskFileUpload();
        upload.setSizeMax(2 * 1024 * 1024);
        List items;
        try {
            items = upload.parseRequest(req);
        } catch (FileUploadException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return;
        }
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (!item.isFormField()) {
                if (item.getSize() > 2 * 1024 * 1024) {
                    continue;
                }
                m_log.fine("Size of uploaded license is [" + item.getSize() + "]");
                try {
                    license = item.getInputStream();
                    licSize = item.getSize();
                    mime = item.getContentType();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                    return;
                }

            } else {
                String name = item.getFieldName();
                String value = item.getString();
                m_log.fine("MC ItemName [" + name + "] Value[" + value + "]");
                if (name != null) {
                    if (name.equals("id")) {
                        id = value;
                        continue;
                    }
                    if (name.equals("userId")) {
                        userId = value;
                        continue;
                    }
                    if (name.equals("contentId")) {
                        contentId = value;
                        continue;
                    }
                    if (name.equals("shopId")) {
                        shopId = value;
                        continue;
                    }

                }
            }

        }
    }
}