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.cornell.mannlib.vitro.webapp.controller.freemarker.ImageUploadHelper.java

/**
 * The image must be present and non-empty, and must have a mime-type that
 * represents an image we support./*from   w  w w . j av  a2 s.c  o  m*/
 * 
 * We rely on the fact that a {@link FileUploadServletRequest} will always
 * have a map of {@link FileItem}s, even if it is empty. However, that map
 * may not contain the field that we want, or that field may contain an
 * empty file.
 * 
 * @throws UserMistakeException
 *             if there is no file, if it is empty, or if it is not an image
 *             file.
 */
FileItem validateImageFromRequest(VitroRequest vreq) throws UserMistakeException {
    Map<String, List<FileItem>> map = vreq.getFiles();
    if (map == null) {
        throw new IllegalStateException(ERROR_CODE_BAD_MULTIPART_REQUEST);
    }

    List<FileItem> list = map.get(PARAMETER_UPLOADED_FILE);
    if ((list == null) || list.isEmpty()) {
        throw new UserMistakeException(ERROR_CODE_FORM_FIELD_MISSING, PARAMETER_UPLOADED_FILE);
    }

    FileItem file = list.get(0);
    if (file.getSize() == 0) {
        throw new UserMistakeException(ERROR_CODE_NO_PHOTO_SELECTED);
    }

    String filename = getSimpleFilename(file);
    String mimeType = getMimeType(file);
    if (!RECOGNIZED_FILE_TYPES.containsValue(mimeType)) {
        log.debug("Unrecognized MIME type: '" + mimeType + "'");
        throw new UserMistakeException(ERROR_CODE_UNRECOGNIZED_FILE_TYPE, filename);
    }

    return file;
}

From source file:com.exedio.cope.live.MediaServlet.java

void doRequest(final HttpServletRequest request, final HttpServletResponse response, final Anchor anchor) {
    final String featureID = request.getParameter(FEATURE);
    if (featureID == null)
        throw new NullPointerException();
    final Media feature = (Media) model.getFeature(featureID);
    if (feature == null)
        throw new NullPointerException(featureID);

    final String itemID = request.getParameter(ITEM);
    if (itemID == null)
        throw new NullPointerException();

    final Item item;
    try {/*w ww  .  j a  v a 2  s.com*/
        startTransaction("media(" + featureID + ',' + itemID + ')');
        item = model.getItem(itemID);
        model.commit();
    } catch (final NoSuchIDException e) {
        throw new RuntimeException(e);
    } finally {
        model.rollbackIfNotCommitted();
    }

    final FileItem fi = anchor.getModification(feature, item);
    if (fi == null)
        throw new NullPointerException(featureID + '-' + itemID);
    response.setContentType(fi.getContentType());
    response.setContentLength((int) fi.getSize());

    InputStream in = null;
    ServletOutputStream out = null;
    try {
        in = fi.getInputStream();
        out = response.getOutputStream();

        final byte[] b = new byte[20 * 1024];
        for (int len = in.read(b); len >= 0; len = in.read(b))
            out.write(b, 0, len);
    } catch (final IOException e) {
        throw new RuntimeException(e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }
        if (out != null) {
            try {
                out.close();
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:UploadImage.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // change the following parameters to connect to the oracle database
    String username = "patzelt";
    String password = "Chocolate1";
    String drivername = "oracle.jdbc.driver.OracleDriver";
    String dbstring = "jdbc:oracle:thin:@gwynne.cs.ualberta.ca:1521:CRS";
    int photo_id;

    try {/*from   ww  w  .j  a v  a 2 s  .  c om*/
        // Parse the HTTP request to get the image stream
        DiskFileUpload fu = new DiskFileUpload();
        List FileItems = fu.parseRequest(request);

        // Process the uploaded items, assuming only 1 image file uploaded
        Iterator i = FileItems.iterator();
        FileItem item = (FileItem) i.next();
        while (i.hasNext() && item.isFormField()) {
            item = (FileItem) i.next();
        }
        long size = item.getSize();

        // Get the image stream
        InputStream instream = item.getInputStream();

        // Connect to the database and create a statement
        Connection conn = getConnected(drivername, dbstring, username, password);
        Statement stmt = conn.createStatement();

        /*
         * First, to generate a unique pic_id using an SQL sequence
         */
        ResultSet rset1 = stmt.executeQuery("SELECT pic_id_sequence.nextval from dual"); // good
        rset1.next();
        photo_id = rset1.getInt(1);
        /**
        // Insert an empty blob into the table first. Note that you have to
        // use the Oracle specific function empty_blob() to create an empty
        // blob
        stmt.execute("INSERT INTO pictures (photo_id, pic_des, pic) VALUES(" + photo_id + ",'test',empty_blob())");
                
        // to retrieve the lob_locator
        // Note that you must use "FOR UPDATE" in the select statement
        String cmd = "SELECT * FROM pictures WHERE photo_id = " + photo_id + " FOR UPDATE";
        ResultSet rset = stmt.executeQuery(cmd);
        rset.next();
        BLOB myblob = ((OracleResultSet) rset).getBLOB(3);
                
        **/

        stmt.execute("INSERT INTO pictures VALUES(" + photo_id + ",'test',empty_blob())");

        PreparedStatement stmt1 = conn
                .prepareStatement("UPDATE pictures SET pic = ? WHERE photo_id = + " + photo_id);
        stmt1.setBinaryStream(1, instream);
        stmt1.executeUpdate();

        /**
        // Write the image to the blob object
        OutputStream outstream = myblob.setBinaryStream(size);
        //int bufferSize = myblob.getBufferSize();
        //byte[] buffer = new byte[bufferSize];
        //int length = -1;
        //while ((length = instream.read(buffer)) != -1)
           //outstream.write(buffer, 0, length);
        outstream.write(pic);
        instream.close();
        outstream.close();
                
        //String update = "UPDATE pictures SET pic = " + myblob + " WHERE photo_id = " + photo_id;
        //stmt.execute(update);
        **/

        response_message = "YAHHOOOOOO";
        conn.close();

    } catch (Exception ex) {
        // System.out.println( ex.getMessage());
        response_message = ex.getMessage();
    }

    // Output response to the client
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n" + "<HTML>\n"
            + "<HEAD><TITLE>Upload Message</TITLE></HEAD>\n" + "<BODY>\n" + "<H1>" + response_message
            + "</H1>\n" + "</BODY></HTML>");
}

From source file:com.ylife.goods.model.UploadImgUpyun.java

/**
 * //from w ww  .  j  a  v  a  2s .  c om
 * 
 * @param item
 * @return ?
 */
public String uploadForRichEdit(FileItem item, UpyunConf upConf) {
    String resoult = null;
    if (item != null && item.getSize() != 0) {
        // ??java?
        @SuppressWarnings("unused")
        boolean flag = false;

        // ???????????
        String fileNamess = UploadImgCommon.getPicNamePathSuffix();

        File file = new File(fileNamess);
        try {
            item.write(file);
            if (upConf != null) {
                YunBean yb = new YunBean();
                yb.setBucketName(upConf.getBucketName());
                yb.setPassword(upConf.getPassWord());
                yb.setUserName(upConf.getUserName());
                UpYunUtil.yunUp(fileNamess, UploadImgCommon.prefix, yb, UploadImgCommon.suffix);
                // ??
                //LOGGER.debug(LOGGERINFO1 + upConf.getUrlPath() + UploadImgCommon.prefix + UploadImgCommon.suffix);
                resoult = upConf.getUrlPath() + UploadImgCommon.prefix + UploadImgCommon.suffix;
            } else {
                flag = true;
            }
        } catch (IllegalStateException e) {
            //LOGGER.error(LOGGERINFO4, e);
            flag = true;
        } catch (IOException e) {
            //LOGGER.error(LOGGERINFO4, e);
            flag = true;
        } catch (Exception e) {
            //LOGGER.error(LOGGERINFO4, e);
            flag = true;
        }
        return resoult;
    } else {
        return null;
    }
}

From source file:fr.paris.lutece.plugins.directory.business.AbstractEntryTypeUpload.java

/**
 * {@inheritDoc}/* w ww.  j a  v  a 2 s .  c o  m*/
 */
@Override
public void canUploadFiles(List<FileItem> listUploadedFileItems, List<FileItem> listFileItemsToUpload,
        Locale locale) throws DirectoryErrorException {
    /** 1) Check max files */
    Field fieldMaxFiles = DirectoryUtils.findFieldByTitleInTheList(CONSTANT_MAX_FILES, getFields());

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

    if ((fieldMaxFiles != null) && StringUtils.isNotBlank(fieldMaxFiles.getValue())
            && StringUtils.isNumeric(fieldMaxFiles.getValue())) {
        nMaxFiles = DirectoryUtils.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);
            throw new DirectoryErrorException(this.getTitle(), strMessage);
        }
    }

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

    if ((fieldFileMaxSize != null) && StringUtils.isNotBlank(fieldFileMaxSize.getValue())
            && StringUtils.isNumeric(fieldFileMaxSize.getValue())) {
        nMaxSize = DirectoryUtils.convertStringToInt(fieldFileMaxSize.getValue());
    } else {
        // For version 2.0.13 and below, the max size was stored in the width of the field "option" for EntryTypeDownloadUrl
        Field fieldOption = DirectoryUtils.findFieldByTitleInTheList(EntryTypeDownloadUrl.CONSTANT_OPTION,
                getFields());

        if (fieldOption != null) {
            nMaxSize = fieldOption.getWidth();
        }
    }

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

    // If nMaxSize == -1, then no size limit
    if ((nMaxSize != DirectoryUtils.CONSTANT_ID_NULL) && (listFileItemsToUpload != null)
            && !listFileItemsToUpload.isEmpty()) {
        for (FileItem fileItem : listFileItemsToUpload) {
            if (fileItem.getSize() > nMaxSize) {
                Object[] params = { nMaxSize };
                String strMessage = I18nService.getLocalizedString(
                        PROPERTY_MESSAGE_ERROR_UPLOADING_FILE_FILE_MAX_SIZE, params, locale);
                throw new DirectoryErrorException(this.getTitle(), strMessage);
            }
        }
    }
}

From source file:com.silverpeas.gallery.ImageHelper.java

/**
 * @param fileHandler/*from   ww  w.  j  a va 2  s  . c om*/
 * @param photo
 * @param image
 * @param watermark
 * @param watermarkHD
 * @param watermarkOther
 * @throws Exception
 */
public static void processImage(final FileHandler fileHandler, final PhotoDetail photo, final FileItem image,
        final boolean watermark, final String watermarkHD, final String watermarkOther) throws Exception {
    final String photoId = photo.getPhotoPK().getId();
    final String instanceId = photo.getPhotoPK().getInstanceId();

    if (image != null) {
        String name = image.getName();
        if (name != null) {
            name = FileUtil.getFilename(name);
            if (ImageType.isImage(name)) {
                final String subDirectory = gallerySettings.getString("imagesSubDirectory");
                final HandledFile handledImageFile = fileHandler.getHandledFile(BASE_PATH, instanceId,
                        subDirectory + photoId, name);
                handledImageFile.writeByteArrayToFile(image.get());
                photo.setImageName(name);
                photo.setImageMimeType(image.getContentType());
                photo.setImageSize(image.getSize());
                createImage(name, handledImageFile, photo, watermark, watermarkHD, watermarkOther);
            }
        }
    }
}

From source file:fr.aliasource.webmail.server.UploadAttachmentsImpl.java

@SuppressWarnings("rawtypes")
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    RequestContext ctx = new ServletRequestContext(req);
    String enc = ctx.getCharacterEncoding();
    logger.warn("received encoding is " + enc);
    if (enc == null) {
        enc = "utf-8";
    }/*from  w  ww . j  a  v  a2s.  c om*/
    IAccount account = (IAccount) req.getSession().getAttribute("account");

    if (account == null) {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    DiskFileItemFactory factory = new DiskFileItemFactory(100 * 1024,
            new File(System.getProperty("java.io.tmpdir")));
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(20 * 1024 * 1024);

    List items = null;
    try {
        items = upload.parseRequest(req);
    } catch (FileUploadException e1) {
        logger.error("upload exception", e1);
        return;
    }

    // Process the uploaded items
    String id = null;
    Iterator iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

        if (!item.isFormField()) {
            id = item.getFieldName();
            String fileName = removePathElementsFromFilename(item.getName());
            logger.warn("FileItem: " + item);
            long size = item.getSize();
            logger.warn("pushing upload of " + fileName + " to backend for " + account.getLogin() + "@"
                    + account.getDomain() + " size: " + size + ").");
            AttachmentMetadata meta = new AttachmentMetadata();
            meta.setFileName(fileName);
            meta.setSize(size);
            meta.setMime(item.getContentType());
            try {
                account.uploadAttachement(id, meta, item.getInputStream());
            } catch (Exception e) {
                logger.error("Cannot write uploaded file to disk");
            }
        }
    }
}

From source file:it.eng.spagobi.tools.catalogue.service.SaveArtifactAction.java

private void checkUploadedFile(FileItem uploaded) {
    logger.debug("IN");
    try {/*w w  w  .  j  a va 2 s  . co m*/
        // check if the uploaded file exceeds the maximum dimension
        int maxSize = GeneralUtilities.getTemplateMaxSize();
        if (uploaded.getSize() > maxSize) {
            throw new SpagoBIEngineServiceException(getActionName(),
                    "The uploaded file exceeds the maximum size, that is " + maxSize);
        }
    } finally {
        logger.debug("OUT");
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.validators.BasicValidation.java

private String validate(String validationType, List<FileItem> fileItems) {
    if ("nonempty".equalsIgnoreCase(validationType)) {
        if (fileItems == null || fileItems.size() == 0) {
            return "a file must be entered for this field.";
        } else {/*  w  ww.j  a v  a 2s . c o  m*/
            FileItem fileItem = fileItems.get(0);
            if (fileItem == null || fileItem.getName() == null || fileItem.getName().length() < 1
                    || fileItem.getSize() < 0) {
                return "a file must be entered for this field.";
            }
        }
    }
    return null;
}

From source file:br.com.caelum.vraptor.observer.upload.CommonsUploadMultipartObserver.java

protected void processFile(FileItem item, String name, MutableRequest request) {
    try {/*from   w w w  .ja va2  s. c  o  m*/
        String fileName = FilenameUtils.getName(item.getName());
        UploadedFile upload = new DefaultUploadedFile(item.getInputStream(), fileName, item.getContentType(),
                item.getSize());
        request.setParameter(name, name);
        request.setAttribute(name, upload);

        logger.debug("Uploaded file: {} with {}", name, upload);
    } catch (IOException e) {
        throw new InvalidParameterException("Cant parse uploaded file " + item.getName(), e);
    }
}