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

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

Introduction

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

Prototype

String getName();

Source Link

Document

Returns the original filename in the client's filesystem, as provided by the browser (or other client software).

Usage

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

/**
 * ????,//from   w w w.  ja v  a 2 s . co m
 * 
 * @param file
 *            FileItem
 * @return ?true?false
 */
private static boolean checkFile(FileItem file) {
    boolean bool = true;
    // ?
    if (file.getSize() > maxSize) {
        //LOGGER.error("=============>" + file.getFieldName() + "??");
        bool = false;
    }
    String fileName = file.getName();
    // ??
    String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
    if (!Arrays.<String>asList(extMap.get(IMAGE).split(",")).contains(fileExt)) {
        //LOGGER.error("" + file.getFieldName() + "??????\n??" + extMap.get(IMAGE) + "?");
        bool = false;
    }
    return bool;
}

From source file:com.zving.cms.site.Site.java

public static void uploadSite(HttpServletRequest request, HttpServletResponse response) {
    try {/*w w w.j a  va 2 s .com*/
        DiskFileItemFactory fileFactory = new DiskFileItemFactory();
        ServletFileUpload fu = new ServletFileUpload(fileFactory);
        List fileItems = fu.parseRequest(request);
        fu.setHeaderEncoding("UTF-8");
        Iterator iter = fileItems.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (!(item.isFormField())) {
                String OldFileName = item.getName();
                LogUtil.info("Upload Site FileName:" + OldFileName);
                long size = item.getSize();
                if ((((OldFileName == null) || (OldFileName.equals("")))) && (size == 0L)) {
                    continue;
                }
                OldFileName = OldFileName.substring(OldFileName.lastIndexOf("\\") + 1);
                String ext = OldFileName.substring(OldFileName.lastIndexOf("."));
                if (!(ext.toLowerCase().equals(".dat"))) {
                    response.sendRedirect("SiteImportStep1.jsp?Error=1");
                    return;
                }
                String FileName = "SiteUpload_" + DateUtil.getCurrentDate("yyyyMMddHHmmss") + ".dat";
                String Path = Config.getContextRealPath() + "WEB-INF/data/backup/";
                item.write(new File(Path + FileName));
                response.sendRedirect("SiteImportStep2.jsp?FileName=" + FileName);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:it.eng.spagobi.commons.utilities.PortletUtilities.java

/**
 * Gets the first uploaded file from a portlet request. This method creates a new file upload handler, 
 * parses the request, processes the uploaded items and then returns the first file as an
 * <code>UploadedFile</code> object.
 * @param portletRequest The input portlet request
 * @return   The first uploaded file object.
 *///from  w w w.j av a2 s  .c  om
public static UploadedFile getFirstUploadedFile(PortletRequest portletRequest) {
    UploadedFile uploadedFile = null;
    try {

        DiskFileItemFactory factory = new DiskFileItemFactory();
        //       Create a new file upload handler
        PortletFileUpload upload = new PortletFileUpload(factory);

        //       Parse the request
        List /* FileItem */ items = upload.parseRequest((ActionRequest) portletRequest);

        //       Process the uploaded items
        Iterator iter = items.iterator();
        boolean endLoop = false;
        while (iter.hasNext() && !endLoop) {
            FileItem item = (FileItem) iter.next();

            if (item.isFormField()) {
                //serviceRequest.setAttribute(item.getFieldName(), item.getString());
            } else {
                uploadedFile = new UploadedFile();
                uploadedFile.setFileContent(item.get());
                uploadedFile.setFieldNameInForm(item.getFieldName());
                uploadedFile.setSizeInBytes(item.getSize());
                uploadedFile.setFileName(item.getName());

                endLoop = true;
            }
        }
    } catch (Exception e) {
        logger.error("Cannot parse multipart request", e);
    }
    return uploadedFile;

}

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

public static void parseRequest(HttpServletRequest request, HashMap<String, String> arrParam,
        ArrayList<FileItem> fi, boolean fileUpload, HashMap<Integer, String> filemap) throws ServiceException {
    DiskFileUpload fu = new DiskFileUpload();
    FileItem fi1 = null;
    List fileItems = null;//from ww w  . jav  a 2s . c o  m
    int i = 0;
    try {
        fileItems = fu.parseRequest(request);
    } catch (FileUploadException e) {
        throw ServiceException.FAILURE("Admin.createUser", e);
    }
    for (Iterator k = fileItems.iterator(); k.hasNext();) {
        fi1 = (FileItem) k.next();
        try {
            if (fi1.isFormField()) {
                arrParam.put(fi1.getFieldName(), fi1.getString("UTF-8"));
            } else {

                String fileName = new String(fi1.getName().getBytes(), "UTF8");
                if (fi1.getSize() != 0) {
                    fi.add(fi1);
                    filemap.put(i, fi1.getFieldName());
                    i++;
                    fileUpload = true;
                }
            }
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        }
    }
}

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:com.silverpeas.gallery.MediaHelper.java

/**
 * Saves uploaded photo file on file system with associated thumbnails and watermarks.
 * @param fileHandler/*ww  w .  java 2 s  .c o  m*/
 * @param photo
 * @param image
 * @param watermark
 * @param watermarkHD
 * @param watermarkOther
 * @throws Exception
 */
public static void processPhoto(final FileHandler fileHandler, final Photo photo, final FileItem image,
        final boolean watermark, final String watermarkHD, final String watermarkOther) throws Exception {
    if (image != null) {
        String name = image.getName();
        if (name != null) {
            try {
                photo.setFileName(FileUtil.getFilename(name));
                final HandledFile handledImageFile = getHandledFile(fileHandler, photo);
                handledImageFile.copyInputStreamToFile(image.getInputStream());
                if (setInternalMetadata(handledImageFile, photo, MediaMimeType.PHOTOS)) {
                    createPhoto(handledImageFile, photo, watermark, watermarkHD, watermarkOther);
                }
            } finally {
                image.delete();
            }
        }
    }
}

From source file:com.example.app.support.AppUtil.java

/**
 * Get the file extension for the given {@link FileItem}.
 *
 * @param file the file to retrieve the file extension for
 *
 * @return the file extension (example: "jpg")
 *///w  ww. j ava2  s .  c o  m
@Nonnull
public static String getExtension(FileItem file) {
    return _getExtensionWithFallback(file.getName(), file.getContentType());
}

From source file:com.xpn.xwiki.web.Utils.java

/**
 * Get the name of an uploaded file, corresponding to the specified form field.
 * /*ww  w  .  j a va2 s . c  om*/
 * @param filelist the list of uploaded files, computed by the FileUpload plugin
 * @param name the name of the form field
 * @return the original name of the file, if the specified field name does correspond to an uploaded file, or
 *         {@code null} otherwise
 */
public static String getFileName(List<FileItem> filelist, String name) {
    for (FileItem item : filelist) {
        if (name.equals(item.getFieldName())) {
            return item.getName();
        }
    }

    return null;
}

From source file:com.dien.upload.server.UploadServlet.java

/**
 * Utility method to get a fileItem from a vector using the file name It
 * only returns items of type file.//from w  w w . j  a  va2  s .  c om
 * 
 * @param sessionFiles
 * @param fileName
 * @return fileItem of the file found or null
 */
public static FileItem findItemByFileName(List<FileItem> sessionFiles, String fileName) {
    if (sessionFiles != null) {
        for (FileItem fileItem : sessionFiles) {
            if (fileItem.isFormField() == false && fileItem.getName().equalsIgnoreCase(fileName)) {
                return fileItem;
            }
        }
    }
    return null;
}

From source file:com.example.app.support.AppUtil.java

/**
 * Get the content type for a {@link FileItem} correcting it based on the file name if the browser didn't provide a
 * content type./* w  ww  .  j  a  v a2s .  c  om*/
 *
 * @param item the item
 *
 * @return the content type
 */
@Nonnull
public static String getContentType(@Nonnull FileItem item) {
    String ct = item.getContentType();

    if (ct == null || "application/octet-stream".equals(ct))
        ct = MimeTypeUtility.getInstance().getContentType(item.getName());

    // In case MimeTypeUtility doesn't do what we wish, it has no API contract.
    if (ct == null)
        ct = "application/octet-stream";

    return ct;
}