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:ned.bcvs.admin.fileupload.VoterFileUploadServlet.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;/*www. j  ava2 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(
            "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>");
                out.println("Uploaded Filepath: " + filePath + fileName + "<br>");
            }
        }
        //calling the ejb method to save voter.csv file to data base
        out.println(upbean.fileDbUploader(filePath + fileName, "voter"));

        out.println("</body>");
        out.println("</html>");
    } catch (Exception ex) {
        System.out.println(ex);
    }
}

From source file:ned.bcvs.admin.fileupload.ElectionPartyFileUploadServlet.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  .  ja va  2  s .c  o 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();
                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>");
            }
        }

        //calling the ejb method to save voter.csv file to data base
        out.println(upbean.fileDbUploader(filePath + fileName, "electionparty"));
        out.println("</body>");
        out.println("</html>");
    } catch (Exception ex) {
        System.out.println(ex);
    }
}

From source file:com.example.web.UploadServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //processRequest(request, response); 

    // Check that we have a file upload request
    isMultipart = ServletFileUpload.isMultipartContent(request);
    //response.setContentType("text/html");
    response.setContentType("text/html;charset=UTF-8");
    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  ww  .ja  v a2  s.  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("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:co.estampas.servlets.guardarEstampa.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from  www  . j  av a  2s .  c  o m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String rutaImg = "NN";
    /*
     SUBIR LA IMAGEN AL SERVIDOR
     */
    dirUploadFiles = getServletContext().getRealPath(getServletContext().getInitParameter("dirUploadFiles"));
    if (ServletFileUpload.isMultipartContent(request)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(new Long(getServletContext().getInitParameter("maxFileSize")).longValue());
        List listUploadFiles = null;
        FileItem item = null;
        try {
            listUploadFiles = upload.parseRequest(request);
            Iterator it = listUploadFiles.iterator();
            while (it.hasNext()) {
                item = (FileItem) it.next();
                if (!item.isFormField()) {
                    if (item.getSize() > 0) {
                        String nombre = item.getName();
                        String extension = nombre.substring(nombre.lastIndexOf("."));
                        File archivo = new File(dirUploadFiles, nombre);
                        item.write(archivo);
                        if (archivo.exists()) {
                            subioImagen = true;
                            rutaImg = "estampas/" + nombre;
                            //                response.sendRedirect("uploadsave.jsp");
                        } else {
                            subioImagen = false;
                        }
                    }
                } else {
                    campos.add(item.getString());
                }
            }
        } catch (FileUploadException e) {
            subioImagen = false;
        } catch (Exception e) {
            subioImagen = false;
        }
    }
    if (subioImagen) {
        String nombreImg = campos.get(1);
        processRequest(request, response);
        EstampaCamiseta estampa = new EstampaCamiseta();
        //BUSCO EL ARTISTA QUE VA A GUARDAR LA ESTAMPA
        this.idArtistax = Integer.parseInt(campos.get(0));
        Artista ar = artistaFacade.find(Integer.parseInt(campos.get(0)));
        estampa.setIdArtista(ar);
        //TRAIGO EL TAMAO QUE ELIGIERON DE LA ESTAMPA
        TamanoEstampa tamEstampa = tamanoEstampaFacade.find(Integer.parseInt(campos.get(4)));
        estampa.setIdTamanoEstampa(tamEstampa);
        //TRAIGO EL TEMA QUE ELIGIERON DE LA ESTAMPA
        TemaEstampa temaEstampa = temaEstampaFacade.find(Integer.parseInt(campos.get(2)));
        estampa.setIdTemaEstampa(temaEstampa);
        //ASIGNO EL NOMBRE DE LA ESTAMPA
        estampa.setDescripcion(nombreImg);
        //ASIGNO LA RUTA DE LA IMAGEN QUE CREO
        estampa.setImagenes(rutaImg);
        //ASIGNO LA UBICACION DE LA IMAGEN EN LA CAMISA
        estampa.setUbicacion(campos.get(5));
        //ASIGNO EL PRECIO DE LA IMAGEN QUE CREO
        estampa.setPrecio(campos.get(3));
        //ASIGNO EL ID DEL LUGAR 
        estampa.setIdLugarEstampa(Integer.parseInt(campos.get(5)));
        //GUARDAR LA ESTAMPA
        estampaCamisetaFacade.create(estampa);
    } else {
        System.out.println("Error al subir imagen");
    }
    campos = new ArrayList<>();

    processRequest(request, response);
}

From source file:com.xpn.xwiki.plugin.fileupload.FileUploadPlugin.java

/**
 * Retrieve the size of a file content in byte. {@link #loadFileList(XWikiContext)} needs to be called beforehand.
 * //  w ww .j ava2s . c  o  m
 * @param formfieldName The name of the form field.
 * @param context Context of the request.
 * @return the size of the file in byte
 * @since 2.3M2
 */
public int getFileItemSize(String formfieldName, XWikiContext context) {
    FileItem fileitem = getFile(formfieldName, context);

    if (fileitem == null) {
        return 0;
    }

    return ((int) fileitem.getSize());
}

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

public void doPost(List fileItems, String filename, String destinationDirectory) {
    File destDir = new File(destinationDirectory);
    Ext = "";/*from  w  w  w . java 2 s . c  o  m*/
    if (!destDir.exists()) {
        destDir.mkdirs();
    }
    DiskFileUpload fu = new DiskFileUpload();
    fu.setSizeMax(-1);
    fu.setSizeThreshold(4096);
    fu.setRepositoryPath(destinationDirectory);
    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) {
                    this.isUploaded = true;
                    File uploadFile = new File(destinationDirectory + "/" + filename + Ext);
                    fi.write(uploadFile);
                    imgResize(destinationDirectory + "/" + filename + Ext, 100, 100,
                            destinationDirectory + "/" + filename + "_100");
                    imgResize(destinationDirectory + "/" + filename + Ext, 35, 35,
                            destinationDirectory + "/" + filename);

                } else {
                    this.isUploaded = false;
                }
            } catch (Exception e) {
                logger.warn(e.getMessage(), e);
            }
        }
    }

}

From source file:com.softwarementors.extjs.djn.demo.FormPostDemo.java

@DirectFormPostMethod
public Result djnform_handleSubmit(Map<String, String> formParameters, Map<String, FileItem> fileFields)
        throws IOException {
    assert formParameters != null;
    assert fileFields != null;

    Result result = new Result();

    StringBuilder fieldNamesAndValues = new StringBuilder("<p>Non file fields:</p>");
    for (Map.Entry<String, String> entry : formParameters.entrySet()) {
        String fieldName = entry.getKey();
        String value = entry.getValue();
        StringBuilderUtils.appendAll(fieldNamesAndValues, "<b>", fieldName, "</b>='", value, "'<br>");
    }/* w  ww  .  jav  a 2  s . com*/

    fieldNamesAndValues.append("<p></p><p>FILE fields:</p>");
    for (Map.Entry<String, FileItem> entry : fileFields.entrySet()) {
        String fieldName = entry.getKey();
        FileItem fileItem = entry.getValue();
        result.fileContents = IOUtils.toString(fileItem.getInputStream());
        fileItem.getInputStream().close();
        StringBuilderUtils.appendAll(fieldNamesAndValues, "<b>", fieldName, "</b>:");

        boolean fileChosen = !fileItem.getName().equals("");
        if (fileChosen) {
            StringBuilderUtils.appendAll(fieldNamesAndValues, " file=", fileItem.getName(), " (size=",
                    Long.toString(fileItem.getSize()), ")");
        } else {
            fieldNamesAndValues.append(" --no file was chosen--");
        }
    }

    result.fieldNamesAndValues = fieldNamesAndValues.toString();
    result.success = true;
    return result;
}

From source file:com.alibaba.citrus.service.requestcontext.parser.impl.ParameterParserImpl.java

/**
 * <code>FileItem</code>/*from  www  .  j  ava2 s . co m*/
 *
 * @param key   ???
 * @param value ?
 */
public void add(String key, FileItem value) {
    if (value.isFormField()) {
        add(key, value.getString());
    } else {
        // 
        if (!StringUtil.isEmpty(value.getName()) || value.getSize() > 0) {
            add(key, (Object) value);
        }
    }
}

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

public void doPostCompay(List fileItems, String filename, String destinationDirectory) {
    File destDir = new File(destinationDirectory);
    Ext = "";/*from   w  w  w. j av  a  2  s. c  o m*/
    if (!destDir.exists()) {
        destDir.mkdirs();
    }
    DiskFileUpload fu = new DiskFileUpload();
    fu.setSizeMax(-1);
    fu.setSizeThreshold(4096);
    fu.setRepositoryPath(destinationDirectory);
    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) {
                    this.isUploaded = true;
                    File uploadFile = new File(destinationDirectory + "/" + "temp_" + filename + Ext);
                    fi.write(uploadFile);
                    imgResizeCompany(destinationDirectory + "/" + "temp_" + filename + Ext, 0, 0,
                            destinationDirectory + "/original_" + filename, true);
                    imgResizeCompany(destinationDirectory + "/" + "temp_" + filename + Ext, 130, 25,
                            destinationDirectory + "/" + filename, false);
                    //                  imgResize(destinationDirectory + "/" + filename + Ext,
                    //                        0, 0, destinationDirectory + "/original_" + filename);
                    uploadFile.delete();
                } else {
                    this.isUploaded = false;
                }
            } catch (Exception e) {
                this.ErrorMsg = "Problem occured while uploading logo";
                logger.warn(e.getMessage(), e);
            }
        }
    }
}

From source file:com.exilant.exility.core.XLSHandler.java

/**
 * @param req/*w w  w.  j av  a  2s  . c  o  m*/
 * @param container
 * @return whether we are able to parse it
 */
@SuppressWarnings("unchecked")
public static boolean parseMultiPartData(HttpServletRequest req, ServiceData container) {
    /**
     * I didnt check here for multipart request ?. caller should check.
     */
    DiskFileItemFactory factory = new DiskFileItemFactory();
    /*
     * we can increase the in memory size to hold the file data but its
     * inefficient so ignoring to factory.setSizeThreshold(20*1024);
     */
    ServletFileUpload sFileUpload = new ServletFileUpload(factory);
    List<FileItem> items = null;

    try {
        items = sFileUpload.parseRequest(req);
    } catch (FileUploadException e) {
        container.addMessage("fileUploadFailed", e.getMessage());
        Spit.out(e);
        return false;
    }

    /*
     * If user is asked for multiple file upload with filesPathGridName then
     * create a grid with below columns and send to the client/DC
     */
    String filesPathGridName = req.getHeader("filesPathGridName");
    OutputColumn[] columns = { new OutputColumn("fileName", DataValueType.TEXT, "fileName"),
            new OutputColumn("fileSize", DataValueType.INTEGRAL, "fileSize"),
            new OutputColumn("filePath", DataValueType.TEXT, "filePath") };
    Value[] columnValues = null;

    FileItem f = null;
    String allowMultiple = req.getHeader("allowMultiple");

    List<Value[]> rows = new ArrayList<Value[]>();

    String fileNameWithPath = "";
    String rootPath = getResourcePath();

    String fileName = null;

    int fileCount = 0;

    for (FileItem item : items) {
        if (item.isFormField()) {
            String name = item.getFieldName();
            container.addValue(name, item.getString());
        } else {
            f = item;
            if (allowMultiple != null) {
                fileCount++;
                fileName = item.getName();
                fileNameWithPath = rootPath + getUniqueName(fileName);

                String path = XLSHandler.write(item, fileNameWithPath, container);
                if (path == null) {
                    return false;
                }

                if (filesPathGridName != null && filesPathGridName.length() > 0) {
                    columnValues = new Value[3];
                    columnValues[0] = Value.newValue(fileName);
                    columnValues[1] = Value.newValue(f.getSize());
                    columnValues[2] = Value.newValue(fileNameWithPath);
                    rows.add(columnValues);
                    fileNameWithPath = "";
                    continue;
                }

                container.addValue("file" + fileCount + "_ExilityPath", fileNameWithPath);
                fileNameWithPath = "";
            }

        }
    }

    if (f != null && allowMultiple == null) {
        fileNameWithPath = rootPath + getUniqueName(f.getName());
        String path = XLSHandler.write(f, fileNameWithPath, container);
        if (path == null) {
            return false;
        }
        container.addValue(container.getValue("fileFieldName"), path);
        return true;
    }

    /**
     * If user asked for multiple file upload and has supplied gridName for
     * holding the file path then create a grid
     */

    if (rows.size() > 0) {
        Grid aGrid = new Grid(filesPathGridName);
        aGrid.setValues(columns, rows, null);

        container.addGrid(filesPathGridName, aGrid.getRawData());
    }
    return true;
}