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.silverpeas.thumbnail.control.ThumbnailController.java

public static boolean processThumbnail(ForeignPK pk, String objectType, List<FileItem> parameters)
        throws Exception {
    boolean thumbnailChanged = false;
    String mimeType = null;/* www.  j ava2 s.  c o m*/
    String physicalName = null;
    FileItem uploadedFile = FileUploadUtil.getFile(parameters, "WAIMGVAR0");
    if (uploadedFile != null) {
        String logicalName = uploadedFile.getName().replace('\\', '/');
        if (StringUtil.isDefined(logicalName)) {
            logicalName = FilenameUtils.getName(logicalName);
            mimeType = FileUtil.getMimeType(logicalName);
            String type = FileRepositoryManager.getFileExtension(logicalName);
            if (FileUtil.isImage(logicalName)) {
                physicalName = String.valueOf(System.currentTimeMillis()) + '.' + type;
                SilverpeasFileDescriptor descriptor = new SilverpeasFileDescriptor(pk.getInstanceId())
                        .mimeType(mimeType).parentDirectory(publicationSettings.getString("imagesSubDirectory"))
                        .fileName(physicalName);
                SilverpeasFile target = SilverpeasFileProvider.newFile(descriptor);
                target.writeFrom(uploadedFile.getInputStream());
            } else {
                throw new ThumbnailRuntimeException("ThumbnailController.processThumbnail()",
                        SilverpeasRuntimeException.ERROR, "thumbnail_EX_MSG_WRONG_TYPE_ERROR");
            }
        }
    }

    // If no image have been uploaded, check if one have been picked up from a gallery
    if (physicalName == null) {
        // on a pas d'image, regarder s'il y a une provenant de la galerie
        String nameImageFromGallery = FileUploadUtil.getParameter(parameters, "valueImageGallery");
        if (StringUtil.isDefined(nameImageFromGallery)) {
            physicalName = nameImageFromGallery;
            mimeType = "image/jpeg";
        }
    }

    // If one image is defined, save it through Thumbnail service
    if (StringUtil.isDefined(physicalName)) {
        ThumbnailDetail detail = new ThumbnailDetail(pk.getInstanceId(), Integer.parseInt(pk.getId()),
                ThumbnailDetail.THUMBNAIL_OBJECTTYPE_PUBLICATION_VIGNETTE);
        detail.setOriginalFileName(physicalName);
        detail.setMimeType(mimeType);
        try {
            ThumbnailController.updateThumbnail(detail);
            thumbnailChanged = true;
        } catch (ThumbnailRuntimeException e) {
            SilverTrace.error("thumbnail", "KmeliaRequestRouter.processVignette",
                    "thumbnail_MSG_UPDATE_THUMBNAIL_KO", e);
            try {
                ThumbnailController.deleteThumbnail(detail);
            } catch (Exception exp) {
                SilverTrace.info("thumbnail", "KmeliaRequestRouter.processVignette",
                        "thumbnail_MSG_DELETE_THUMBNAIL_KO", exp);
            }
        }
    }
    return thumbnailChanged;
}

From source file:com.aaasec.sigserv.csspserver.utility.SpServerLogic.java

public static String processFileUpload(HttpServletRequest request, HttpServletResponse response,
        RequestModel req) {// w  w  w .j  av  a  2  s .  co  m
    // Create a factory for disk-based file items
    Map<String, String> paraMap = new HashMap<String, String>();
    File uploadedFile = null;
    boolean uploaded = false;
    DiskFileItemFactory factory = new DiskFileItemFactory();
    String uploadDirName = FileOps.getfileNameString(SpModel.getDataDir(), "uploads");
    FileOps.createDir(uploadDirName);
    File storageDir = new File(uploadDirName);
    factory.setRepository(storageDir);

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    try {
        // Parse the request
        List<FileItem> items = upload.parseRequest(request);
        for (FileItem item : items) {
            if (item.isFormField()) {
                String name = item.getFieldName();
                String value = item.getString();
                paraMap.put(name, value);
            } else {
                String fieldName = item.getFieldName();
                String fileName = item.getName();
                if (fileName.length() > 0) {
                    String contentType = item.getContentType();
                    boolean isInMemory = item.isInMemory();
                    long sizeInBytes = item.getSize();
                    uploadedFile = new File(storageDir, fileName);
                    try {
                        item.write(uploadedFile);
                        uploaded = true;
                    } catch (Exception ex) {
                        LOG.log(Level.SEVERE, null, ex);
                    }
                }
            }

        }
        if (uploaded) {
            return SpServerLogic.getDocUploadResponse(req, uploadedFile);
        } else {
            if (paraMap.containsKey("xmlName")) {
                return SpServerLogic.getServerDocResponse(req, paraMap.get("xmlName"));
            }
        }
    } catch (FileUploadException ex) {
        LOG.log(Level.SEVERE, null, ex);
    }
    response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    return "";
}

From source file:edu.isi.webserver.FileUtil.java

static public File downloadFileFromHTTPRequest(HttpServletRequest request) {
    // Download the file to the upload file folder
    File destinationDir = new File(DESTINATION_DIR_PATH);
    logger.info("File upload destination directory: " + destinationDir.getAbsolutePath());
    if (!destinationDir.isDirectory()) {
        destinationDir.mkdir();/*from   w w  w  .j  a  v  a  2s.  co m*/
    }

    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();

    // Set the size threshold, above which content will be stored on disk.
    fileItemFactory.setSizeThreshold(1 * 1024 * 1024); //1 MB

    //Set the temporary directory to store the uploaded files of size above threshold.
    fileItemFactory.setRepository(destinationDir);

    ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);

    File uploadedFile = null;
    try {
        // Parse the request
        @SuppressWarnings("rawtypes")
        List items = uploadHandler.parseRequest(request);
        @SuppressWarnings("rawtypes")
        Iterator itr = items.iterator();
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();

            // Ignore Form Fields.
            if (item.isFormField()) {
                System.out.println(item.getFieldName());
                System.out.println(item.getString());
                // Do nothing
            } else {
                //Handle Uploaded files. Write file to the ultimate location.
                System.out.println("File field name: " + item.getFieldName());
                uploadedFile = new File(destinationDir, item.getName());
                item.write(uploadedFile);
                System.out.println("File written to: " + uploadedFile.getAbsolutePath());
            }
        }
    } catch (FileUploadException ex) {
        logger.error("Error encountered while parsing the request", ex);
    } catch (Exception ex) {
        logger.error("Error encountered while uploading file", ex);
    }
    return uploadedFile;
}

From source file:com.google.caja.ancillary.servlet.UploadPage.java

static void doUpload(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // Process the uploaded items
    List<ObjectConstructor> uploads = Lists.newArrayList();

    if (ServletFileUpload.isMultipartContent(req)) {
        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        int maxUploadSizeBytes = 1 << 18;
        factory.setSizeThreshold(maxUploadSizeBytes); // In-memory threshold
        factory.setRepository(new File("/dev/null")); // Do not store on disk
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(maxUploadSizeBytes);

        writeHeader(resp);/*from   ww  w.ja  v  a2  s.  co m*/

        // Parse the request
        List<?> items;
        try {
            items = upload.parseRequest(req);
        } catch (FileUploadException ex) {
            ex.printStackTrace();
            resp.getWriter().write(Nodes.encode(ex.getMessage()));
            return;
        }

        for (Object fileItemObj : items) {
            FileItem item = (FileItem) fileItemObj; // Written for pre-generic java.
            if (!item.isFormField()) { // Then is a file
                FilePosition unk = FilePosition.UNKNOWN;
                String ct = item.getContentType();
                uploads.add((ObjectConstructor) QuasiBuilder.substV("({ i: @i, ip: @ip, it: @it? })", "i",
                        StringLiteral.valueOf(unk, item.getString()), "ip",
                        StringLiteral.valueOf(unk, item.getName()), "it",
                        ct != null ? StringLiteral.valueOf(unk, ct) : null));
            }
        }
    } else if (req.getParameter("url") != null) {
        List<URI> toFetch = Lists.newArrayList();
        boolean failed = false;
        for (String value : req.getParameterValues("url")) {
            try {
                toFetch.add(new URI(value));
            } catch (URISyntaxException ex) {
                if (!failed) {
                    failed = true;
                    resp.setStatus(500);
                    resp.setContentType("text/html;charset=UTF-8");
                }
                resp.getWriter().write("<p>Bad URI: " + Nodes.encode(ex.getMessage()));
            }
        }
        if (failed) {
            return;
        }
        writeHeader(resp);
        FilePosition unk = FilePosition.UNKNOWN;
        for (URI uri : toFetch) {
            try {
                Content c = UriFetcher.fetch(uri);
                if (c.isText()) {
                    uploads.add((ObjectConstructor) QuasiBuilder.substV("({ i: @i, ip: @ip, it: @it? })", "i",
                            StringLiteral.valueOf(unk, c.getText()), "ip",
                            StringLiteral.valueOf(unk, uri.toString()), "it",
                            StringLiteral.valueOf(unk, c.type.mimeType)));
                }
            } catch (IOException ex) {
                resp.getWriter()
                        .write("<p>" + Nodes.encode("Failed to fetch URI: " + uri + " : " + ex.getMessage()));
            }
        }
    } else {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        resp.getWriter().write("Content not multipart");
        return;
    }

    Expression notifyParent = (Expression) QuasiBuilder.substV(
            "window.parent.uploaded([@uploads*], window.name)", "uploads", new ParseTreeNodeContainer(uploads));
    StringBuilder jsBuf = new StringBuilder();
    RenderContext rc = new RenderContext(new JsMinimalPrinter(new Concatenator(jsBuf))).withEmbeddable(true);
    notifyParent.render(rc);
    rc.getOut().noMoreTokens();

    HtmlQuasiBuilder b = HtmlQuasiBuilder.getBuilder(DomParser.makeDocument(null, null));

    Writer out = resp.getWriter();
    out.write(Nodes.render(b.substV("<script>@js</script>", "js", jsBuf.toString())));
}

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

/**
 * Saves uploaded sound file on file system
 * @param fileHandler//from   w ww.jav  a  2 s . c om
 * @param sound the current sound media
 * @param fileItem the current uploaded sound
 * @throws Exception
 */
public static void processSound(final FileHandler fileHandler, Sound sound, final FileItem fileItem)
        throws Exception {
    if (fileItem != null) {
        String name = fileItem.getName();
        if (name != null) {
            try {
                sound.setFileName(FileUtil.getFilename(name));
                final HandledFile handledSoundFile = getHandledFile(fileHandler, sound);
                handledSoundFile.copyInputStreamToFile(fileItem.getInputStream());
                setInternalMetadata(handledSoundFile, sound, MediaMimeType.SOUNDS);
            } finally {
                fileItem.delete();
            }
        }
    }
}

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

/**
 * Saves uploaded video file on file system
 * @param fileHandler/*from   www  .  j  ava2  s  .co m*/
 * @param video the current video media
 * @param fileItem the current uploaded video
 * @throws Exception
 */
public static void processVideo(final FileHandler fileHandler, Video video, final FileItem fileItem)
        throws Exception {
    if (fileItem != null) {
        String name = fileItem.getName();
        if (name != null) {
            try {
                video.setFileName(FileUtil.getFilename(name));
                final HandledFile handledVideoFile = getHandledFile(fileHandler, video);
                handledVideoFile.copyInputStreamToFile(fileItem.getInputStream());
                setInternalMetadata(handledVideoFile, video, MediaMimeType.VIDEOS);
                generateVideoThumbnails(handledVideoFile.getFile());
            } finally {
                fileItem.delete();
            }
        }
    }
}

From source file:jeeves.server.sources.ServiceRequestFactory.java

private static Element getMultipartParams(HttpServletRequest req, String uploadDir, int maxUploadSize)
        throws Exception {
    Element params = new Element("params");

    DiskFileItemFactory fif = new DiskFileItemFactory();
    ServletFileUpload sfu = new ServletFileUpload(fif);

    sfu.setSizeMax(((long) maxUploadSize) * 1024L * 1024L);

    try {/*from  ww w  . j a v  a 2s.  c  om*/
        for (Object i : sfu.parseRequest(req)) {
            FileItem item = (FileItem) i;
            String name = item.getFieldName();

            if (item.isFormField()) {
                String encoding = req.getCharacterEncoding();
                params.addContent(new Element(name).setText(item.getString(encoding)));
            } else {
                String file = item.getName();
                String type = item.getContentType();
                long size = item.getSize();

                if (Log.isDebugEnabled(Log.REQUEST))
                    Log.debug(Log.REQUEST, "Uploading file " + file + " type: " + type + " size: " + size);
                //--- remove path information from file (some browsers put it, like IE)

                file = simplifyName(file);
                if (Log.isDebugEnabled(Log.REQUEST))
                    Log.debug(Log.REQUEST, "File is called " + file + " after simplification");

                //--- we could get troubles if 2 users upload files with the same name
                item.write(new File(uploadDir, file));

                Element elem = new Element(name).setAttribute("type", "file")
                        .setAttribute("size", Long.toString(size)).setText(file);

                if (type != null)
                    elem.setAttribute("content-type", type);

                if (Log.isDebugEnabled(Log.REQUEST))
                    Log.debug(Log.REQUEST, "Adding to parameters: " + Xml.getString(elem));
                params.addContent(elem);
            }
        }
    } catch (FileUploadBase.SizeLimitExceededException e) {
        throw new FileUploadTooBigEx();
    }

    return params;
}

From source file:jeeves.server.sources.JeevletServiceRequestFactory.java

private static Element getMultipartParams(Request req, String uploadDir, int maxUploadSize) throws Exception {

    Element params = new Element("params");

    // FIXME FileUpload - confirm only "multipart/form-data" entities must be parsed here ...
    // if (entity != null && MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) {

    // The Apache FileUpload project parses HTTP requests which
    // conform to RFC 1867, "Form-based File Upload in HTML". That
    // is, if an HTTP request is submitted using the POST method,
    // and with a content type of "multipart/form-data", then
    // FileUpload can parse that request, and get all uploaded files
    // as FileItem.

    // 1/ Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(1000240); // en mmoire
    factory.setRepository(new File(uploadDir));

    // 2/ Create a new file upload handler based on the Restlet
    // FileUpload extension that will parse Restlet requests and
    // generates FileItems.
    RestletFileUpload upload = new RestletFileUpload(factory);

    upload.setFileSizeMax(maxUploadSize * 1024 * 1024);

    List<FileItem> items;//from  w w w.java 2  s  .c o  m
    try {
        items = upload.parseRequest(req);// parseRepresentation(req.getEntity());

        for (final Iterator<FileItem> it = items.iterator(); it.hasNext();) {
            FileItem item = (FileItem) it.next();

            String name = item.getFieldName();

            if (item.isFormField())
                params.addContent(new Element(name).setText(item.getString()));
            else {
                String file = item.getName();
                String type = item.getContentType();
                long size = item.getSize();
                Log.debug(Log.REQUEST, "Uploading file " + file + " type: " + type + " size: " + size);
                //--- remove path information from file (some browsers put it, like IE)

                file = simplifyName(file);
                Log.debug(Log.REQUEST, "File is called " + file + " after simplification");

                //--- we could get troubles if 2 users upload files with the same name
                item.write(new File(uploadDir, file));

                Element elem = new Element(name).setAttribute("type", "file")
                        .setAttribute("size", Long.toString(size)).setText(file);

                if (type != null)
                    elem.setAttribute("content-type", type);

                Log.debug(Log.REQUEST, "Adding to parameters: " + Xml.getString(elem));
                params.addContent(elem);
            }
        }
    } catch (FileUploadBase.FileSizeLimitExceededException e) {
        // throw jeeves exception --> reached code ? see apache docs -
        // FileUploadBase
        throw new FileUploadTooBigEx();
    } catch (FileUploadException e) {
        // Sample Restlet ... " 

        // The message of all thrown exception is sent back to client as simple plain text
        // response.setEntity(new StringRepresentation(e.getMessage(), MediaType.TEXT_PLAIN));
        // response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
        // e.printStackTrace();

        // " ... now throw a JeevletException but
        // FIXME must throw Exception with a correct Status
        throw new JeevletException(e);
    }

    return params;
}

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

public static void parseRequest(HttpServletRequest request, HashMap<String, String> arrParam,
        ArrayList<FileItem> fi, boolean fileUpload) throws ServiceException {
    DiskFileUpload fu = new DiskFileUpload();
    FileItem fi1 = null;
    List fileItems = null;/*ww w .  j  av  a 2 s .co m*/
    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();
        if (fi1.isFormField()) {
            arrParam.put(fi1.getFieldName(), fi1.getString());
        } else {
            try {
                String fileName = new String(fi1.getName().getBytes(), "UTF8");
                if (fi1.getSize() != 0) {
                    fi.add(fi1);
                    fileUpload = true;
                }
            } catch (UnsupportedEncodingException ex) {
            }
        }
    }
}

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

/**
 * @param req/*from   w  w  w  .j ava 2s .  com*/
 * @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;
}