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.hzc.framework.ssh.controller.WebUtil.java

/**
 * jsonp?/*  w w w  . j a v a  2 s  .  c o  m*/
 *  + ?
 *
 * @param path
 * @param ufc
 * @return
 * @throws Exception
 */
public static <T> T uploadMultiAndProgress(String path, Class<T> c, UploadFileNewCall ufc,
        final ProgressListener pl) throws RuntimeException {
    try {
        HttpServletRequest request = getReq();
        //            final HttpSession session = getSession();
        ServletContext servletContext = getServletContext();
        File file = new File(servletContext.getRealPath(path));
        if (!file.exists())
            file.mkdir();

        DiskFileItemFactory fac = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(fac);
        upload.setHeaderEncoding("UTF-8");
        upload.setProgressListener(pl);
        List<FileItem> fileItems = upload.parseRequest(request);

        T obj = c.newInstance();
        Field[] declaredFields = c.getDeclaredFields();
        for (FileItem item : fileItems) {
            if (!item.isFormField()) {

                String name = item.getName();
                String type = item.getContentType();
                if (StringUtils.isNotBlank(name)) {
                    File f = new File(file + File.separator + name);
                    item.write(f);
                    ufc.file(obj, f, name, name, item.getSize(), type); // ????
                }
            } else {

                String name = item.getFieldName();
                // ??,??
                for (Field field : declaredFields) {
                    field.setAccessible(true);
                    String fieldName = field.getName();
                    if (name.equals(fieldName)) {
                        String value = item.getString("UTF-8");
                        if (null == value) {
                            continue;
                        }
                        Class<?> type = field.getType();
                        if (type == Long.class) {
                            field.set(obj, Long.parseLong(value));
                        } else if (type == String.class) {
                            field.set(obj, value);
                        } else if (type == Byte.class) {
                            field.set(obj, Byte.parseByte(value));
                        } else if (type == Integer.class) {
                            field.set(obj, Integer.parseInt(value));
                        } else if (type == Character.class) {
                            field.set(obj, value.charAt(0));
                        } else if (type == Boolean.class) {
                            field.set(obj, Boolean.parseBoolean(value));
                        } else if (type == Double.class) {
                            field.set(obj, Double.parseDouble(value));
                        } else if (type == Float.class) {
                            field.set(obj, Float.parseFloat(value));
                        }
                    }
                }
            }
        }
        return obj;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:edu.fullerton.ldvservlet.Upload.java

private int addFile(FileItem item, HashMap<String, String> params, Page vpage, String userName,
        ImageTable imageTable) throws ServletException {
    int ret = 0;/*from w  ww . j  ava  2 s.  c o m*/

    String fieldName = item.getFieldName();
    String fileName = item.getName();
    String contentType = item.getContentType();
    boolean isInMemory = item.isInMemory();
    long sizeInBytes = item.getSize();
    if (sizeInBytes >= 100 && !fileName.isEmpty()) {
        Matcher m = fileNumPat.matcher(fieldName);
        if (m.find()) {
            String descriptionName = "desc" + m.group(1);
            String description = params.get(descriptionName);
            description = description == null ? "" : description;
            if (isValid(contentType)) {
                try {
                    byte[] buf = item.get();
                    ByteArrayInputStream bis = new ByteArrayInputStream(buf);
                    int imgId = imageTable.addImg(userName, bis, contentType);
                    if (!description.isEmpty()) {
                        imageTable.addDescription(imgId, description);
                    }
                    ret = imgId;
                    vpage.add("uploaded " + fileName + " - " + description);
                    vpage.addBlankLines(1);
                } catch (IOException | SQLException | NoSuchAlgorithmException ex) {
                    String ermsg = "Error reading data for " + fileName + ex.getClass().getSimpleName() + " "
                            + ex.getLocalizedMessage();
                    vpage.add(ermsg);
                    vpage.addBlankLines(1);
                }
            } else {
                vpage.add(String.format("The file: %1$s has an unsuported mime type: %2$s", fileName,
                        contentType));
                vpage.addBlankLines(1);
            }
        }
    }
    return ret;
}

From source file:com.javaweb.controller.ThemTinTucServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request/* w  w w  .ja v  a2  s. c  om*/
 * @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, ParseException {
    response.setContentType("text/html;charset=UTF-8");
    request.setCharacterEncoding("UTF-8");

    //response.setCharacterEncoding("UTF-8");
    HttpSession session = request.getSession();
    //        session.removeAttribute("errorreg");
    String TieuDe = "", NoiDung = "", ngaydang = "", GhiChu = "", fileName = "";
    int idloaitin = 0, idTK = 0;

    TintucService tintucservice = new TintucService();

    //File upload
    String folderupload = getServletContext().getInitParameter("file-upload");
    String rootPath = getServletContext().getRealPath("/");
    filePath = rootPath + folderupload;
    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();

    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:\\Windows\\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();

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

                //change file name
                fileName = FileService.ChangeFileName(fileName);

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

            if (fi.isFormField()) {
                if (fi.getFieldName().equalsIgnoreCase("TieuDe")) {
                    TieuDe = fi.getString("UTF-8");
                } else if (fi.getFieldName().equalsIgnoreCase("NoiDung")) {
                    NoiDung = fi.getString("UTF-8");
                } else if (fi.getFieldName().equalsIgnoreCase("NgayDang")) {
                    ngaydang = fi.getString("UTF-8");
                } else if (fi.getFieldName().equalsIgnoreCase("GhiChu")) {
                    GhiChu = fi.getString("UTF-8");
                } else if (fi.getFieldName().equalsIgnoreCase("loaitin")) {
                    idloaitin = Integer.parseInt(fi.getString("UTF-8"));
                } else if (fi.getFieldName().equalsIgnoreCase("idtaikhoan")) {
                    idTK = Integer.parseInt(fi.getString("UTF-8"));
                }
            }
        }

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

    Date NgayDang = new SimpleDateFormat("yyyy-MM-dd").parse(ngaydang);
    Tintuc tintuc = new Tintuc(idloaitin, idTK, fileName, TieuDe, NoiDung, NgayDang, GhiChu);

    boolean rs = tintucservice.InsertTintuc(tintuc);
    if (rs) {
        session.setAttribute("kiemtra", "1");
        String url = "ThemTinTuc.jsp";
        response.sendRedirect(url);
    } else {
        session.setAttribute("kiemtra", "0");
        String url = "ThemTinTuc.jsp";
        response.sendRedirect(url);
    }

    //        try (PrintWriter out = response.getWriter()) {
    //            /* TODO output your page here. You may use following sample code. */
    //            out.println("<!DOCTYPE html>");
    //            out.println("<html>");
    //            out.println("<head>");
    //            out.println("<title>Servlet ThemTinTucServlet</title>");            
    //            out.println("</head>");
    //            out.println("<body>");
    //            out.println("<h1>Servlet ThemTinTucServlet at " + request.getContextPath() + "</h1>");
    //            out.println("</body>");
    //            out.println("</html>");
    //        }
}

From source file:javaclasses.adminclass.java

public boolean insertnews(String t, String n, String d, String time, FileItem file) throws IOException {
    connect();//ww w.j a  v  a2 s . co  m
    try {
        String news;
        news = n.trim();
        st = con.prepareCall("{call prcInsertNews(?,?,?,?,?)}");
        st.setString(1, t);
        st.setString(2, news);
        st.setString(3, d);
        st.setString(4, time);
        st.setBinaryStream(5, file.getInputStream(), (int) file.getSize());
        if (st.execute() == false) {
            disconnect();
            return true;
        }
    } catch (SQLException e) {
        System.out.println(e);
    } catch (NumberFormatException e) {
        System.out.println(e);
    }
    return false;
}

From source file:com.picdrop.service.implementation.FileResourceService.java

@POST
@Path("/")
@Permission("write")
@Consumes("multipart/form-data")
public List<FileResource> create(@Context HttpServletRequest request) throws ApplicationException {
    log.traceEntry();/* w  ww  . j  ava2 s  .  co  m*/
    List<FileResource> res = new ArrayList<>();
    List<FileItem> files;

    log.debug(SERVICE, "Parsing multipart request");
    try {
        files = parseRequest(request);
    } catch (FileUploadException ex) {
        throw new ApplicationException(ex).status(400).devMessage(ex.getMessage())
                .code(ErrorMessageCode.BAD_UPLOAD);
    }

    log.debug(SERVICE, "Processing file items");
    for (FileItem file : files) {
        if (!file.isFormField()) {
            validateFileItem(file);

            FileResource r = new FileResource();
            r.setName(file.getName());
            r.setSize(file.getSize());
            r.setOwner(contextProv.get().getPrincipal().to(RegisteredUser.class));

            try {
                log.debug(SERVICE, "Validating mime type");
                FileType mime = parseMimeType(file);

                r.setDescriptor(ResourceDescriptor.get(mime));

                res.add(processCreateUpdate(r, file));
            } catch (IOException ex) {
                throw new ApplicationException(ex).status(500).devMessage(ex.getMessage())
                        .code(ErrorMessageCode.ERROR_INTERNAL);
            }
        }
    }
    log.info(SERVICE, "FileResource created");
    log.traceExit(res);
    return res;
}

From source file:com.controller.RecipeImage.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* ww w.  ja v a2s .  com*/
 *
 * @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 {
    response.setContentType("text/html;charset=UTF-8");

    //retrieving the path to store image from web.xml
    filePath = getServletContext().getInitParameter("recipeImageStorePath");

    //retrieving the path to display image from web.xml
    fileDisplay = getServletContext().getInitParameter("recipeImageDisplayPath");

    // 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;
    }
    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>");
        out.println("1");
        while (i.hasNext()) {
            out.println("2");
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                fileName = fi.getName();
                fileName = randomString(fileName);
                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>" + filePath);
            } else {
                out.println("No file");
            }
        }
        out.println("</body>");
        out.println("</html>");

        RecipeBean recipeBean = new RecipeBean();
        RecipeDAO recipeDAO = new RecipeDAO();

        String image = fileDisplay + "" + fileName;
        out.println(image);

        HttpSession session = request.getSession();
        String recipeId = (String) session.getAttribute("recipeId");
        session.removeAttribute("recipeId");
        recipeDAO.addImage(recipeId, image);

        response.sendRedirect("Home");

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

From source file:com.eufar.asmm.server.UploadImage.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println("UploadImage - the function started");
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(MAX_MEMORY_SIZE);
    String uploadFolder = getServletContext().getRealPath("") + DATA_DIRECTORY;
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(MAX_REQUEST_SIZE);
    double maxSize = (MAX_REQUEST_SIZE / 1024) / 1024;
    System.out.println("UploadImage - max image size: " + maxSize + " Mbytes");
    try {//from  ww  w.j  a v a  2  s .  c  om
        @SuppressWarnings("rawtypes")
        List items = upload.parseRequest(request);
        @SuppressWarnings("rawtypes")
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            Object obj = iter.next();
            org.apache.commons.fileupload.FileItem item = (org.apache.commons.fileupload.FileItem) obj;
            String fileExt = FilenameUtils.getExtension(item.getName());
            if (fileExt.matches("(jpg|jpeg|bmp|png|JPG|JPEG|BMP|PNG)")) {
                System.out.println("UploadImage - image accepted");
                if (!item.isFormField()) {
                    File uploadedFile = File.createTempFile("tmp_", "." + fileExt, new File(uploadFolder));
                    item.write(uploadedFile);
                    double fileSize = item.getSize();
                    fileSize = (fileSize / 1024) / 1024;
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("text/html");
                    response.getWriter().write(uploadedFile.getName());
                    System.out.println("UploadImage - " + uploadedFile.getPath() + ": upload ok...");
                    System.out.println("UploadImage - " + uploadedFile.getPath() + ": " + fileSize + " MBytes");
                    if (new File(uploadedFile.getPath()).isFile()) {
                        System.out.println("PrintFunction - picture (webapps): the file exists.");
                    } else {
                        System.out.println("PrintFunction - picture (webapps): the file doesn't exist.");
                    }
                    if (new File(uploadedFile.getPath()).isFile()) {
                        System.out.println("PrintFunction - picture (webapps): the file can be read.");
                    } else {
                        System.out.println("PrintFunction - picture (webapps): the file can't be read.");
                    }
                } else {
                    System.out.println("UploadImage - a problem occured with the file format");
                }
            } else {
                System.out.println("UploadImage - image rejected: wrong format");
                response.setCharacterEncoding("UTF-8");
                response.setContentType("text/html");
                response.getWriter().write("format");
            }
        }
    } catch (Exception ex) {
        System.out.println("UploadImage - a problem occured: " + ex);
        response.getWriter().write("ERROR:" + ex.getMessage());
    }
}

From source file:fr.paris.lutece.plugins.genericattributes.service.upload.AbstractGenAttUploadHandler.java

/**
 * {@inheritDoc}/*  w  w  w  . j  a v a  2 s . c o  m*/
 */
@Override
public void addFileItemToUploadedFilesList(FileItem fileItem, String strFieldName, HttpServletRequest request) {
    // This is the name that will be displayed in the form. We keep
    // the original name, but clean it to make it cross-platform.
    String strFileName = UploadUtil.cleanFileName(fileItem.getName().trim());

    initMap(request.getSession().getId(), buildFieldName(strFieldName));

    // Check if this file has not already been uploaded
    List<FileItem> uploadedFiles = getListUploadedFiles(strFieldName, request.getSession());

    if (uploadedFiles != null) {
        boolean bNew = true;

        if (!uploadedFiles.isEmpty()) {
            Iterator<FileItem> iterUploadedFiles = uploadedFiles.iterator();

            while (bNew && iterUploadedFiles.hasNext()) {
                FileItem uploadedFile = iterUploadedFiles.next();
                String strUploadedFileName = UploadUtil.cleanFileName(uploadedFile.getName().trim());
                // If we find a file with the same name and the same
                // length, we consider that the current file has
                // already been uploaded
                bNew = !(StringUtils.equals(strUploadedFileName, strFileName)
                        && (uploadedFile.getSize() == fileItem.getSize()));
            }
        }

        if (bNew) {
            uploadedFiles.add(fileItem);
        }
    }
}

From source file:edu.umd.cs.submitServer.servlets.UploadTestSetup.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // TODO sanity checks on the format of the test setup
    MultipartRequest multipartRequest = (MultipartRequest) request.getAttribute(MULTIPART_REQUEST);
    Connection conn = null;/*from w  ww.  ja  v a2 s . co  m*/
    FileItem fileItem = null;
    boolean transactionSuccess = false;
    try {
        conn = getConnection();

        fileItem = multipartRequest.getFileItem();
        if (fileItem == null)
            throw new ServletException("fileItem is null; this is not good");

        Project project = (Project) request.getAttribute(PROJECT);
        // could be null
        String comment = multipartRequest.getOptionalCheckedParameter("comment");

        // get size in bytes
        long sizeInBytes = fileItem.getSize();
        if (sizeInBytes == 0) {
            throw new ServletException("Trying upload file of size 0");
        }

        // copy the fileItem into a byte array
        InputStream is = fileItem.getInputStream();
        ByteArrayOutputStream bytes = new ByteArrayOutputStream((int) sizeInBytes);
        IO.copyStream(is, bytes);

        byte[] byteArray = bytes.toByteArray();

        FormatDescription desc = FormatIdentification.identify(byteArray);
        if (desc == null || !desc.getMimeType().equals("application/zip")) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "You MUST submit test-setups that are either zipped or jarred");
            return;
        }
        Submission canonicalSubmission = Submission
                .lookupMostRecent(project.getCanonicalStudentRegistrationPK(), project.getProjectPK(), conn);
        // start transaction here
        conn.setAutoCommit(false);
        conn.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
        TestSetup.submit(byteArray, project, comment, conn);
        conn.commit();
        transactionSuccess = true;
        if (canonicalSubmission != null
                && canonicalSubmission.getBuildStatus() != Submission.BuildStatus.BROKEN) {
            WaitingBuildServer.offerSubmission(project, canonicalSubmission);
        }

        String redirectUrl = request.getContextPath() + "/view/instructor/projectUtilities.jsp?projectPK="
                + project.getProjectPK();
        response.sendRedirect(redirectUrl);

    } catch (SQLException e) {
        throw new ServletException(e);
    } finally {
        rollbackIfUnsuccessfulAndAlwaysReleaseConnection(transactionSuccess, request, conn);
        releaseConnection(conn);
        if (fileItem != null)
            fileItem.delete();
    }
}

From source file:com.nabla.wapp.server.basic.general.ImportService.java

@Override
public String executeAction(final HttpServletRequest request, final List<FileItem> sessionFiles)
        throws UploadActionException {
    final UserSession userSession = UserSession.load(request);
    if (userSession == null) {
        if (log.isTraceEnabled())
            log.trace("missing user session");
        throw new UploadActionException("permission denied");
    }//from   ww w . j  ava  2s  .  c  om
    Assert.state(sessionFiles.size() == 1);
    try {
        for (FileItem file : sessionFiles) {
            if (file.isFormField())
                continue;
            if (log.isDebugEnabled()) {
                log.debug("field '" + file.getFieldName() + "': uploading " + file.getName());
                log.debug("field: " + file.getFieldName());
                log.debug("filename: " + file.getName());
                log.debug("content_type: " + file.getContentType());
                log.debug("size: " + file.getSize());
            }
            final Connection conn = db.getConnection();
            try {
                final PreparedStatement stmt = conn.prepareStatement(
                        "INSERT INTO import_data (field_name, file_name, content_type, length, content, userSessionId) VALUES(?,?,?,?,?,?);",
                        Statement.RETURN_GENERATED_KEYS);
                try {
                    stmt.setString(1, file.getFieldName());
                    stmt.setString(2, file.getName());
                    stmt.setString(3, file.getContentType());
                    stmt.setLong(4, file.getSize());
                    stmt.setString(6, userSession.getSessionId());
                    final InputStream fs = file.getInputStream();
                    try {
                        stmt.setBinaryStream(5, fs);
                        if (stmt.executeUpdate() != 1) {
                            if (log.isErrorEnabled())
                                log.error("failed to add imported file record");
                            throw new UploadActionException("internal error");
                        }
                        final ResultSet rsKey = stmt.getGeneratedKeys();
                        try {
                            rsKey.next();
                            final Integer id = rsKey.getInt(1);
                            if (log.isDebugEnabled())
                                log.debug(
                                        "uploading " + file.getName() + " successfully completed. id = " + id);
                            return id.toString();
                        } finally {
                            rsKey.close();
                        }
                    } finally {
                        fs.close();
                    }
                } catch (IOException e) {
                    if (log.isErrorEnabled())
                        log.error("error reading file " + file.getName(), e);
                    throw new UploadActionException("internal error");
                } finally {
                    Database.close(stmt);
                }
            } finally {
                // remove any orphan import records i.e. older than 48h (beware of timezone!)
                final Calendar dt = Util.dateToCalendar(new Date());
                dt.add(GregorianCalendar.DATE, -2);
                try {
                    Database.executeUpdate(conn, "DELETE FROM import_data WHERE created < ?;",
                            Util.calendarToSqlDate(dt));
                } catch (final SQLException __) {
                }
                Database.close(conn);
            }
        }
    } catch (SQLException e) {
        if (log.isErrorEnabled())
            log.error("error uploading file", e);
        throw new UploadActionException("internal error");
    } finally {
        super.removeSessionFileItems(request);
    }
    return null;
}