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

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

Introduction

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

Prototype

boolean isInMemory();

Source Link

Document

Provides a hint as to whether or not the file contents will be read from memory.

Usage

From source file:com.bibisco.filters.FileFilter.java

/**
 * Example of how to get useful things with the uploaded file structure.
  * Generally speaking, this method should be overrided by framework's users.
 * /*w w  w  .j a v a 2  s .  c  om*/
 * <p>Here we demostrate how to extract useful infos 
 * (<code>name, value, isInMemory, size, etc) </code>)
 * plus how to deal with memory- or disk-persisted cases.
 * 
 * <li><p>We pass the whole <code>FileItem</code> structure
 * to the next <code>jsp</code> page, which gains the ability to extract 
 * infos as well: via Request, under name: "file-" + fieldname
 * 
 * <li><p>The file content can be retrieved here or later, <code>FileItem</code>
 * object can use its data-getters in <code>.jsp</code>s! 
 * <p>In this code, we retrieve file content and pass it in Request 
 * for next uses under the a general format of 
 * array of bytes (<code>byte []</code>);  with name equal to "file-" + fieldname.  
 *  
 * @param pItem
 * @throws IOException
 */
protected void processUploadedFile(FileItem pItem, ServletRequest pRequest) throws IOException {
    String name = pItem.getFieldName();
    boolean isInMemory = pItem.isInMemory();
    pRequest.setAttribute("file-" + name, pItem);

    if (isInMemory) {
        mLog.debug("the file ", name, " is in memory under the request attribute file-content-", name);
        byte[] data = pItem.get();
        pRequest.setAttribute("file-content-" + name, data);
    } else {
        mLog.debug("the file ", name, " is in the file system and under the request attribute file-content-",
                name);
        InputStream uploadedStream = pItem.getInputStream();
        byte[] data = (new StreamTokenizer(new BufferedReader(new InputStreamReader(uploadedStream))))
                .toString().getBytes();
        uploadedStream.close();
        pRequest.setAttribute("file-content-" + name, data);
    }
}

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

/**
 * Compare FileItem's (except the byte[] content)
 *//*from  w w w  .  j  a v  a2s .  c o  m*/
private void compareFileItems(FileItem origItem, FileItem newItem) {
    assertTrue("Compare: is in Memory", origItem.isInMemory() == newItem.isInMemory());
    assertTrue("Compare: is Form Field", origItem.isFormField() == newItem.isFormField());
    assertEquals("Compare: Field Name", origItem.getFieldName(), newItem.getFieldName());
    assertEquals("Compare: Content Type", origItem.getContentType(), newItem.getContentType());
    assertEquals("Compare: File Name", origItem.getName(), newItem.getName());
}

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./*  w ww .  ja va  2  s  . com*/
 */
@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.github.davidcarboni.encryptedfileupload.EncryptedFileItemSerializeTest.java

/**
 * Helper method to test creation of a field when a repository is used.
 *///ww  w .j ava 2 s.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:helma.util.MimePart.java

/**
 * Creates a new MimePart object from a file upload.
 * @param fileItem a commons fileupload file item
 *///from  w ww.  j  av  a  2 s.c  o  m
public MimePart(FileItem fileItem) {
    name = normalizeFilename(fileItem.getName());
    contentType = fileItem.getContentType();
    contentLength = (int) fileItem.getSize();
    if (fileItem.isInMemory()) {
        content = fileItem.get();
    } else {
        this.fileItem = fileItem;
    }
}

From source file:game.com.HandleUploadGameNesServlet.java

private void handle(HttpServletRequest request, AjaxResponseEntity responseObject) throws Exception {
    boolean isMultipart;
    String filePath;/*from www .j  a  v  a 2 s  . c  o m*/
    int maxFileSize = 4 * 1024 * 1024;
    int maxMemSize = 4 * 1024 * 1024;
    File file;

    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("/tmp"));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);
    Map<String, List<FileItem>> postData = upload.parseParameterMap(request);
    String id = postData.get("id").get(0).getString();
    if (StringUtils.isBlank(id)) {
        logger.info("id= " + id);
    }

    try {
        // Parse the request to get file items.
        List<FileItem> fileItems = postData.get("nes");
        // Process the uploaded file items

        for (FileItem fi : fileItems) {
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                String fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();
                // Write the file

                file = new File(AppConfig.OPENSHIFT_DATA_DIR + "/nes/" + id + ".zip");

                fi.write(file);
                responseObject.data = getNesFileUrl(id);
                responseObject.returnCode = 1;
                responseObject.returnMessage = "success";
                break;
            } else {
                logger.info("isFormField " + fi.getFieldName());
            }
        }

    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
    }
}

From source file:com.seer.datacruncher.profiler.spring.FileUploadController.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Check that we have a file upload request
    filePath = this.servletContext.getInitParameter("file-upload");
    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    if (!isMultipart) {
        return null;
    }//from  w ww . j a  v a2s. c om
    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(filePath));

    // 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);

        // Process the uploaded file items
        Iterator i = fileItems.iterator();

        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                String fileName = fi.getName();
                String contentType = fi.getContentType();
                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);
                out.print("{success: true, file: \"" + fileName + "\"}");
                // out.println("{\"file\": " + fileName + "}");
            }
        }

    } catch (Exception ex) {
        System.out.println(ex);
    }
    return null;
}

From source file:com.official.wears.site.UploadServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {
    // Check that we have a file upload request
    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    if (!isMultipart) {
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<p>No file uploaded</p>");
        out.println("</body>");
        out.println("</html>");
        return;/*  w  ww  .j a  va 2 s.co  m*/
    }
    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);

        // Process the uploaded file items
        Iterator i = fileItems.iterator();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                String fileName = fi.getName();
                String contentType = fi.getContentType();
                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);
                out.println("Uploaded Filename: " + fileName + "<br>");
            }
        }
        out.println("</body>");
        out.println("</html>");
    } catch (Exception ex) {
        System.out.println(ex);
    }
}

From source file:game.com.HandleUploadGameThumbServlet.java

private void handle(HttpServletRequest request, AjaxResponseEntity responseObject) throws Exception {
    boolean isMultipart;
    String filePath;//from   w w  w.j  a  va  2s  .co  m
    int maxFileSize = 4 * 1024 * 1024;
    int maxMemSize = 4 * 1024 * 1024;
    File file;

    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("/tmp"));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);
    Map<String, List<FileItem>> postData = upload.parseParameterMap(request);
    String id = postData.get("id").get(0).getString();
    if (StringUtils.isBlank(id)) {
        logger.info("id= " + id);
    }

    try {
        // Parse the request to get file items.
        List<FileItem> fileItems = postData.get("image");
        // Process the uploaded file items

        for (FileItem fi : fileItems) {
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                String fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();
                // Write the file
                file = new File(AppConfig.OPENSHIFT_DATA_DIR + "/thumb/" + id + ".png");
                //                    Image img = ImageIO.read(fi.getInputStream());
                //                    BufferedImage tempPNG = resizeImage(img, 256, 240);
                //                    ImageIO.write(tempPNG, "png", file);
                fi.write(file);
                responseObject.data = getThumbUrl(id);
                responseObject.returnCode = 1;
                responseObject.returnMessage = "success";
                break;
            } else {
                logger.info("isFormField " + fi.getFieldName());
            }
        }

    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
    }
}

From source file:ned.bcvs.admin.fileupload.ConstituencyFileUploadServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {
    // Check that we have a file upload request
    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    if (!isMultipart) {
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<p>No file uploaded</p>");
        out.println("</body>");
        out.println("</html>");
        return;//from  w  w w  .j  av  a 2s .  co  m
    }
    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(
            "D:/glassfish12October/glassfish-4.0/glassfish4/" + "glassfish/domains/domain1/applications/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);

        // Process the uploaded file items
        Iterator i = fileItems.iterator();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                fileName = fi.getName();
                String contentType = fi.getContentType();
                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);
                out.println("Uploaded Filename: " + fileName + "<br>");
            }
        }
        //calling the ejb method to save constituency.csv file to data base
        out.println(upbean.fileDbUploader(filePath + fileName, "constituency"));
        out.println("</body>");
        out.println("</html>");
    } catch (Exception ex) {
        System.out.println(ex);
    }
}