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:edu.harvard.hul.ois.drs.pdfaconvert.service.servlets.PdfaConverterServlet.java

/**
 * Handles the file upload for PdfaConverter processing via streaming of the file
 * using the <code>POST</code> method. Example: curl -X POST -F datafile=@
 * <path/to/file> <host>:[<port>]/pdfa-converter/examine Note: "pdfa-converter" in the above URL
 * needs to be adjusted to the final name of the WAR file.
 *
 * @param request/*from  w  ww . j  a va 2 s .  co  m*/
 *            servlet request
 * @param response
 *            servlet response
 * @throws ServletException
 *             if a servlet-specific error occurs
 * @throws IOException
 *             if an I/O error occurs
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    logger.info("Entering doPost()");
    if (!ServletFileUpload.isMultipartContent(request)) {
        ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_BAD_REQUEST,
                " Missing Multipart Form Data. ", request.getRequestURL().toString());
        sendErrorMessageResponse(errorMessage, response);
        return;
    }

    try {
        List<FileItem> formItems = upload.parseRequest(request);
        Iterator<FileItem> iter = formItems.iterator();

        // iterates over form's fields
        while (iter.hasNext()) {
            FileItem item = iter.next();

            // processes only fields that are not form fields
            // if (!item.isFormField()) {
            if (!item.isFormField() && item.getFieldName().equals(FORM_FIELD_DATAFILE)) {

                long fileSize = item.getSize();
                if (fileSize < 1) {
                    ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_BAD_REQUEST,
                            " Missing File Data. ", request.getRequestURL().toString());
                    sendErrorMessageResponse(errorMessage, response);
                    return;
                }
                // save original uploaded file name
                InputStream inputStream = item.getInputStream();
                String origFileName = item.getName();

                DiskFileItemExt itemExt = new DiskFileItemExt(item.getFieldName(), item.getContentType(),
                        item.isFormField(), item.getName(), (maxInMemoryFileSizeMb * (int) MB_MULTIPLIER),
                        factory.getRepository());
                // Create a temporary unique filename for a file containing the original temp filename plus the real filename containing its file type suffix.
                String tempFilename = itemExt.getTempFile().getName();
                StringBuilder realFileTypeFilename = new StringBuilder(tempFilename);
                realFileTypeFilename.append('-');
                realFileTypeFilename.append(origFileName);
                // create the file in the same temporary directory
                File realInputFile = new File(factory.getRepository(), realFileTypeFilename.toString());

                // strip out suffix before saving to ServletRequestListener
                request.setAttribute(TEMP_FILE_NAME_KEY, tempFilename.substring(0, tempFilename.indexOf('.')));

                // turn InputStream into a File in temp directory
                OutputStream outputStream = new FileOutputStream(realInputFile);
                IOUtils.copy(inputStream, outputStream);
                outputStream.close();

                try {
                    // Send it to the PdfaConverter processor...
                    sendPdfaConverterExamineResponse(realInputFile, origFileName, request, response);
                } finally {
                    // delete both original temporary file -- if large enough will have been persisted to disk -- and our created file
                    if (!item.isInMemory()) { // 
                        item.delete();
                    }
                    if (realInputFile.exists()) {
                        realInputFile.delete();
                    }
                }

            } else {
                ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_BAD_REQUEST,
                        " The request did not have the correct name attribute of \"datafile\" in the form processing. ",
                        request.getRequestURL().toString(), " Processing halted.");
                sendErrorMessageResponse(errorMessage, response);
                return;
            }

        }

    } catch (FileUploadException ex) {
        logger.error(ex);
        ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                " There was an unexpected server error: " + ex.getMessage(), request.getRequestURL().toString(),
                " Processing halted.");
        sendErrorMessageResponse(errorMessage, response);
        return;
    }
}

From source file:com.zlfun.framework.misc.UploadUtils.java

public static byte[] getFileBytes(HttpServletRequest request) {

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    // ???/*w  w  w . ja  va2  s. c o m*/
    // ??
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // ??

    //  ?? 
    factory.setSizeThreshold(1024 * 1024);

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("UTF-8");
    try {
        // ?
        List<FileItem> list = (List<FileItem>) upload.parseRequest(request);

        for (FileItem item : list) {
            // ????
            String name = item.getFieldName();

            // ? ??  ?
            if (item.isFormField()) {
                // ? ?????? 
                String value = new String(item.getString().getBytes("iso-8859-1"), "utf-8");

                request.setAttribute(name, value);
            } // ? ??  
            else {
                /**
                 * ?? ??
                 */
                // ???
                String value = item.getName();
                // ?
                // ????
                value = java.net.URLDecoder.decode(value, "UTF-8");
                int start = value.lastIndexOf("\\");
                // ?  ??1 ???
                String filename = value.substring(start + 1);

                InputStream in = item.getInputStream();
                int length = 0;
                byte[] buf = new byte[1024];
                System.out.println("??" + item.getSize());
                // in.read(buf) ?? buf 
                while ((length = in.read(buf)) != -1) {
                    //  buf  ??  ??
                    out.write(buf, 0, length);
                }

                try {

                    if (in != null) {
                        in.close();
                    }

                } catch (IOException ex) {
                    Logger.getLogger(UploadUtils.class.getName()).log(Level.SEVERE, null, ex);
                }
                return out.toByteArray();

            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        try {
            out.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            Logger.getLogger(UploadUtils.class.getName()).log(Level.SEVERE, null, e);
        }
    }
    return null;

}

From source file:fr.paris.lutece.plugins.genericattributes.service.entrytype.AbstractEntryTypeImage.java

/**
 * {@inheritDoc}//from  w  w  w  . java2  s . com
 */
@Override
public GenericAttributeError canUploadFiles(Entry entry, List<FileItem> listUploadedFileItems,
        List<FileItem> listFileItemsToUpload, Locale locale) {
    /** 1) Check max files */
    Field fieldMaxFiles = GenericAttributesUtils.findFieldByTitleInTheList(CONSTANT_MAX_FILES,
            entry.getFields());

    // By default, max file is set at 1
    int nMaxFiles = 1;

    if ((fieldMaxFiles != null) && StringUtils.isNotBlank(fieldMaxFiles.getValue())
            && StringUtils.isNumeric(fieldMaxFiles.getValue())) {
        nMaxFiles = GenericAttributesUtils.convertStringToInt(fieldMaxFiles.getValue());
    }

    if ((listUploadedFileItems != null) && (listFileItemsToUpload != null)) {
        int nNbFiles = listUploadedFileItems.size() + listFileItemsToUpload.size();

        if (nNbFiles > nMaxFiles) {
            Object[] params = { nMaxFiles };
            String strMessage = I18nService.getLocalizedString(PROPERTY_MESSAGE_ERROR_UPLOADING_FILE_MAX_FILES,
                    params, locale);
            GenericAttributeError error = new GenericAttributeError();
            error.setMandatoryError(false);
            error.setTitleQuestion(entry.getTitle());
            error.setErrorMessage(strMessage);

            return error;
        }
    }

    /** 2) Check files size */
    Field fieldFileMaxSize = GenericAttributesUtils.findFieldByTitleInTheList(CONSTANT_FILE_MAX_SIZE,
            entry.getFields());
    int nMaxSize = GenericAttributesUtils.CONSTANT_ID_NULL;

    if ((fieldFileMaxSize != null) && StringUtils.isNotBlank(fieldFileMaxSize.getValue())
            && StringUtils.isNumeric(fieldFileMaxSize.getValue())) {
        nMaxSize = GenericAttributesUtils.convertStringToInt(fieldFileMaxSize.getValue());
    }

    // If no max size defined in the db, then fetch the default max size from the properties file
    if (nMaxSize == GenericAttributesUtils.CONSTANT_ID_NULL) {
        nMaxSize = AppPropertiesService.getPropertyInt(PROPERTY_UPLOAD_FILE_DEFAULT_MAX_SIZE, 5242880);
    }

    // If nMaxSize == -1, then no size limit
    if ((nMaxSize != GenericAttributesUtils.CONSTANT_ID_NULL) && (listFileItemsToUpload != null)
            && (listUploadedFileItems != null)) {
        boolean bHasFileMaxSizeError = false;
        List<FileItem> listFileItems = new ArrayList<FileItem>();
        listFileItems.addAll(listUploadedFileItems);
        listFileItems.addAll(listFileItemsToUpload);

        for (FileItem fileItem : listFileItems) {
            if (fileItem.getSize() > nMaxSize) {
                bHasFileMaxSizeError = true;

                break;
            }
        }

        if (bHasFileMaxSizeError) {
            Object[] params = { nMaxSize };
            String strMessage = I18nService
                    .getLocalizedString(PROPERTY_MESSAGE_ERROR_UPLOADING_FILE_FILE_MAX_SIZE, params, locale);
            GenericAttributeError error = new GenericAttributeError();
            error.setMandatoryError(false);
            error.setTitleQuestion(entry.getTitle());
            error.setErrorMessage(strMessage);

            return error;
        }
    }

    if (listFileItemsToUpload != null) {
        for (FileItem fileItem : listFileItemsToUpload) {
            if (checkForImages()) {
                GenericAttributeError error = doCheckforImages(fileItem, entry, locale);

                if (error != null) {
                    return error;
                }
            }
        }
    }

    return null;
}

From source file:fr.paris.lutece.plugins.directory.utils.DirectoryUtils.java

/**
 * Get the file contains in the request from the name of the input file
 *
 * @param strFileInputName/*from   w w  w.  j  a v a 2s . c  o m*/
 *            le name of the input file file
 * @param request
 *            the request
 * @return file the file contains in the request from the name of the input
 *         file
 */
public 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:fr.paris.lutece.plugins.document.modules.calendar.web.DocumentToCalendarJspBean.java

/**
 * Manage the files document before create event
 * @param request The HTTP request/*from ww  w . j  a v a2s .c om*/
 */
public void doManageCreateEvent(HttpServletRequest request) {
    String strIdDocument = request.getParameter(PARAMETER_ID_DOCUMENT);

    //If there is a document file
    if ((strIdDocument != null) && !strIdDocument.equals("")) {
        MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
        FileItem item = mRequest.getFile(PARAMETER_EVENT_IMAGE);

        //If this document file is not replace by another file
        if (item.getSize() < 1) {
            Document document = DocumentHome.findByPrimaryKey(Integer.parseInt(strIdDocument));
            DocumentAttribute documentAttribute = document.getAttribute(PARAMETER_TYPE_FILE);

            byte[] fileContent = documentAttribute.getBinaryValue();
            String strMimeType = documentAttribute.getValueContentType();

            HttpSession session = request.getSession(true);
            session.setAttribute(CalendarJspBean.ATTRIBUTE_MODULE_DOCUMENT_TO_CALENDAR_CONTENT_FILE,
                    fileContent);
            session.setAttribute(CalendarJspBean.ATTRIBUTE_MODULE_DOCUMENT_TO_CALENDAR_MIME_TYPE_FILE,
                    strMimeType);
        }
    }
}

From source file:com.orinus.script.safe.jetty.SRequest.java

public void parseMultipartContent() {
    if (formFields != null && formFiles != null && formFileData != null)
        return;//from www .j a  va2  s  . co m
    formFields = new HashMap<String, String>();
    formFiles = new HashMap<String, FileEntry>();
    formFileData = new HashMap<String, String>();
    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        Controller controller = new Controller();
        factory.setRepository(new File(controller.getTempDir()));
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items = upload.parseRequest(req);
        for (int i = 0; i < items.size(); i++) {
            FileItem item = (FileItem) items.get(i);
            if (item.isFormField()) {
                formFields.put(item.getFieldName(), item.getString());
            } else {
                FileEntry fe = new FileEntry();
                fe.fieldName = item.getFieldName();
                fe.contentType = item.getContentType();
                fe.filename = new File(item.getName()).getName();
                fe.fileSize = item.getSize();
                String filename = new File(controller.getTempDir(), fe.filename).getAbsolutePath();
                item.write(new File(filename));
                formFiles.put(fe.fieldName, fe);
                formFileData.put(fe.fieldName, filename);
            }
        }
    } catch (Exception e) {
    }
}

From source file:AES.Controllers.FileController.java

@RequestMapping(value = "/upload", method = RequestMethod.GET)
public void upload(HttpServletResponse response, HttpServletRequest request,
        @RequestParam Map<String, String> requestParams) throws IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    out.println("Hello<br/>");

    boolean isMultipartContent = ServletFileUpload.isMultipartContent(request);
    if (!isMultipartContent) {
        out.println("You are not trying to upload<br/>");
        return;/*from  w w  w .j  ava  2 s. com*/
    }
    out.println("You are trying to upload<br/>");

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    try {
        List<FileItem> fields = upload.parseRequest(request);
        out.println("Number of fields: " + fields.size() + "<br/><br/>");
        Iterator<FileItem> it = fields.iterator();
        if (!it.hasNext()) {
            out.println("No fields found");
            return;
        }
        out.println("<table border=\"1\">");
        while (it.hasNext()) {
            out.println("<tr>");
            FileItem fileItem = it.next();
            boolean isFormField = fileItem.isFormField();
            if (isFormField) {
                out.println("<td>regular form field</td><td>FIELD NAME: " + fileItem.getFieldName()
                        + "<br/>STRING: " + fileItem.getString());
                out.println("</td>");
            } else {
                out.println("<td>file form field</td><td>FIELD NAME: " + fileItem.getFieldName()
                        + "<br/>STRING: " + fileItem.getString() + "<br/>NAME: " + fileItem.getName()
                        + "<br/>CONTENT TYPE: " + fileItem.getContentType() + "<br/>SIZE (BYTES): "
                        + fileItem.getSize() + "<br/>TO STRING: " + fileItem.toString());
                out.println("</td>");
                String path = request.getSession().getServletContext().getRealPath("") + "\\uploads\\";
                //System.out.println(request.getSession().getServletContext().getRealPath(""));
                File f = new File(path + fileItem.getName());
                if (!f.exists())
                    f.createNewFile();
                fileItem.write(f);
            }
            out.println("</tr>");
        }
        out.println("</table>");
    } catch (FileUploadException e) {
        e.printStackTrace();
    } catch (Exception ex) {
        Logger.getLogger(FileController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:cdc.util.Upload.java

public boolean anexos(HttpServletRequest request, HttpServletResponse response) throws Exception {
    if (ServletFileUpload.isMultipartContent(request)) {
        int cont = 0;
        ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
        List fileItemsList = null;
        try {//  w  ww .jav a2 s .c  o  m
            fileItemsList = servletFileUpload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        String optionalFileName = "";
        FileItem fileItem = null;
        Iterator it = fileItemsList.iterator();
        do {
            //cont++;
            FileItem fileItemTemp = (FileItem) it.next();
            if (fileItemTemp.isFormField()) {
                if (fileItemTemp.getFieldName().equals("file")) {
                    optionalFileName = fileItemTemp.getString();
                }
            } else {
                fileItem = fileItemTemp;
            }
            if (cont != (fileItemsList.size())) {
                if (fileItem != null) {
                    String fileName = fileItem.getName();
                    if (fileItem.getSize() > 0) {
                        if (optionalFileName.trim().equals("")) {
                            fileName = FilenameUtils.getName(fileName);
                        } else {
                            fileName = optionalFileName;
                        }
                        String dirName = request.getServletContext().getRealPath(pasta);
                        File saveTo = new File(dirName + fileName);
                        //System.out.println("caminho: " + saveTo.toString() );
                        try {
                            fileItem.write(saveTo);
                        } catch (Exception e) {
                        }
                    }
                }
            }
            cont++;
        } while (it.hasNext());
        return true;
    } else {
        return false;
    }
}

From source file:br.com.sislivros.servlets.RecuperarDadosLivro.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w  w w . j  a v  a 2s  .c o m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    String caminho;
    if (isMultipart) {
        try {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = (List<FileItem>) upload.parseRequest(request);
            for (FileItem item : items) {
                if (item.isFormField()) {
                    response.getWriter().println("Name campo:" + item.getFieldName());
                    response.getWriter().println("Value campo:" + item.getString());
                    request.setAttribute(item.getFieldName(), item.getString());
                } else {
                    //caso seja um campo do tipo file
                    response.getWriter().println("NOT Form field");
                    response.getWriter().println("Name:" + item.getFieldName());
                    response.getWriter().println("FileNam:" + item.getName());
                    response.getWriter().println("Size:" + item.getSize());
                    response.getWriter().println("ContentType:" + item.getContentType());
                    response.getWriter().println(
                            "C:\\uploads" + File.separator + new Date().getTime() + "_" + item.getName());
                    if (item.getName() == "" || item.getName() == null) {
                        caminho = "img" + File.separator + "sis1.jpg";
                    } else {
                        caminho = ("img" + File.separator + new Date().getTime() + "_" + item.getName());
                    }
                    response.getWriter().println("Caminho: " + caminho);
                    request.setAttribute("caminho", caminho);
                    //                        File uploadedFile = new File("C:\\TomCat\\apache-tomcat-8.0.21\\webapps\\sislivros\\img" + caminho);
                    File uploadedFile = new File(
                            "E:\\Documentos\\NetBeansProjects\\sislivrosgit\\sisLivro\\web\\" + caminho);
                    item.write(uploadedFile);
                    request.setAttribute("caminho", caminho);
                    request.getRequestDispatcher("CadastroLivroServlet").forward(request, response);
                }
            }
        } catch (Exception e) {
            response.getWriter().println("ocorreu um problema ao fazer o upload: " + e.getMessage());
        }
    }
}

From source file:edu.pitt.servlets.processAddMedia.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from   www  . j  a va 2  s .  c om*/
 * @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 {

    HttpSession session = request.getSession();
    String userID = (String) session.getAttribute("userID");

    String error = "select correct format ";
    session.setAttribute("error", error);

    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        // Process only if its multipart content
        // Create a factory for disk-based file items
        File file;
        // We might need to play with the file sizes
        int maxFileSize = 50000 * 1024;
        int maxMemSize = 50000 * 1024;
        ServletContext context = this.getServletContext();
        // Note that this file path refers to a virtual path
        // relative to this servlet.  The uploads directory
        // is part of this project.  The physical path varies 
        // from the virtual path

        String filePath = context.getRealPath("/uploads") + "/";
        out.println("Physical folder is located at: " + filePath + "<br />");

        // Verify the content type
        String contentType = request.getContentType();
        // This is very important - make sure that the web form that 
        // uploads the file is actually set to enctype="multipart/form-data"
        // An example of upload form for this project is in index.html
        if ((contentType.indexOf("multipart/form-data") >= 0)) {

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

                        out.println("field name" + fieldName);
                        String fileName = fi.getName();

                        out.println("file name" + fileName); // file name is present

                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();
                        //  out.println("file size"+ sizeInBytes);
                        // 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: " + filePath  + fileName + "<br />");
                        String savepath = filePath + fileName;

                        // to check correct format is entered or not 
                        int dotindex = fileName.indexOf(".");
                        if (!(fileName.substring(dotindex).matches(".ogv|.webm|.mp4|.png|.jpeg|.jpg|.gif"))) {
                            response.sendRedirect("./pages/addMedia.jsp");

                        }

                        // receives projectID from listProjects.jsp from edit href link , adding in existing project 
                        // corresponding constructor is used          
                        if (session.getAttribute("projectID") != null) {
                            Integer projectID = (Integer) session.getAttribute("projectID");

                            media = new Media(projectID, fileName);
                        }
                        // first time when user enters media for project , this constructor is used          
                        else {
                            media = new Media(userID, fileName);
                        }

                        System.out.println("Into the media constructor");
                        // redirected to listProject
                        response.sendRedirect("./pages/listProject.jsp");

                        // media constructor

                        // response.redirect(listprojects.jsp);

                        processRequest(request, response);
                    }

                }

            }

            catch (FileUploadException ex) {
                Logger.getLogger(processAddMedia.class.getName()).log(Level.SEVERE, null, ex);
            } catch (Exception ex) {
                Logger.getLogger(processAddMedia.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}