Example usage for org.apache.commons.fileupload FileItemStream getContentType

List of usage examples for org.apache.commons.fileupload FileItemStream getContentType

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItemStream getContentType.

Prototype

String getContentType();

Source Link

Document

Returns the content type passed by the browser or null if not defined.

Usage

From source file:com.woonoz.proxy.servlet.HttpEntityEnclosingRequestHandler.java

private String getContentTypeForFileItem(FileItemStream fileItem) {
    final String contentType = fileItem.getContentType();
    if (contentType != null) {
        return contentType;
    } else {/*from w w  w  .ja v  a2 s  . c  om*/
        if (fileItem.isFormField()) {
            return "text/plain";
        } else {
            return "application/octet-stream";
        }
    }
}

From source file:com.fizzbuzz.vroom.sample.webservice.api.resource.ImagesResource.java

@Override
protected void validateFileItemStream(final FileItemStream fileItemStream) {
    super.validateFileItemStream(fileItemStream);
    String contentType = fileItemStream.getContentType();
    if (!(contentType.equals(MediaType.IMAGE_PNG.getName()))
            || contentType.equals(MediaType.IMAGE_GIF.getName())) {
        throw new IllegalArgumentException("image content type must be either image/png or image/gif");
    }/* ww  w . j  a va2  s . co  m*/

}

From source file:guru.nidi.ramltester.util.FormDecoder.java

private Object valueOf(FileItemStream itemStream) throws IOException {
    if (itemStream.isFormField()) {
        final String charset = charset(itemStream.getContentType());
        return IoUtils.readIntoString(new InputStreamReader(itemStream.openStream(), charset));
    }//from  w ww.j ava 2  s  . c o m
    return new FileValue();
}

From source file:com.cubusmail.gwtui.server.services.AttachmentUploadServlet.java

/**
 * Create a MimeBodyPart.//from w w  w. j a  va 2s.c  o  m
 * 
 * @param item
 * @return
 * @throws MessagingException
 * @throws IOException
 */
private DataSource createDataSource(FileItemStream item) throws MessagingException, IOException {

    final String fileName = FilenameUtils.getName(item.getName());
    final String contentType = item.getContentType();
    final InputStream stream = item.openStream();

    ByteArrayDataSource source = new ByteArrayDataSource(stream, contentType);
    source.setName(fileName);

    return source;
}

From source file:echopoint.tucana.JakartaCommonsFileUploadProvider.java

/**
 * @see UploadSPI#handleUpload(nextapp.echo.webcontainer.Connection ,
 *      FileUploadSelector, String, UploadProgress)
 *//*from  w  w  w  .  j  av a2s  .c o m*/
@SuppressWarnings({ "ThrowableInstanceNeverThrown" })
public void handleUpload(final Connection conn, final FileUploadSelector uploadSelect, final String uploadIndex,
        final UploadProgress progress) throws Exception {
    final ApplicationInstance app = conn.getUserInstance().getApplicationInstance();

    final DiskFileItemFactory itemFactory = new DiskFileItemFactory();
    itemFactory.setRepository(getDiskCacheLocation());
    itemFactory.setSizeThreshold(getMemoryCacheThreshold());

    String encoding = conn.getRequest().getCharacterEncoding();
    if (encoding == null) {
        encoding = "UTF-8";
    }

    final ServletFileUpload upload = new ServletFileUpload(itemFactory);
    upload.setHeaderEncoding(encoding);
    upload.setProgressListener(new UploadProgressListener(progress));

    long sizeLimit = uploadSelect.getUploadSizeLimit();
    if (sizeLimit == 0)
        sizeLimit = getFileUploadSizeLimit();
    if (sizeLimit != NO_SIZE_LIMIT) {
        upload.setSizeMax(sizeLimit);
    }

    String fileName = null;
    String contentType = null;

    try {
        final FileItemIterator iter = upload.getItemIterator(conn.getRequest());
        if (iter.hasNext()) {
            final FileItemStream stream = iter.next();

            if (!stream.isFormField()) {
                fileName = FilenameUtils.getName(stream.getName());
                contentType = stream.getContentType();

                final Set<String> types = uploadSelect.getContentTypeFilter();
                if (!types.isEmpty()) {
                    if (!types.contains(contentType)) {
                        app.enqueueTask(uploadSelect.getTaskQueue(), new InvalidContentTypeRunnable(
                                uploadSelect, uploadIndex, fileName, contentType, progress));
                        return;
                    }
                }

                progress.setStatus(Status.inprogress);
                final FileItem item = itemFactory.createItem(fileName, contentType, false, stream.getName());
                item.getOutputStream(); // initialise DiskFileItem internals

                uploadSelect.notifyCallback(
                        new UploadStartEvent(uploadSelect, uploadIndex, fileName, contentType, item.getSize()));

                IOUtils.copy(stream.openStream(), item.getOutputStream());

                app.enqueueTask(uploadSelect.getTaskQueue(),
                        new FinishRunnable(uploadSelect, uploadIndex, fileName, item, progress));

                return;
            }
        }

        app.enqueueTask(uploadSelect.getTaskQueue(), new FailRunnable(uploadSelect, uploadIndex, fileName,
                contentType, new RuntimeException("No multi-part content!"), progress));
    } catch (final FileUploadBase.SizeLimitExceededException e) {
        app.enqueueTask(uploadSelect.getTaskQueue(), new FailRunnable(uploadSelect, uploadIndex, fileName,
                contentType, new UploadSizeLimitExceededException(e), progress));
    } catch (final FileUploadBase.FileSizeLimitExceededException e) {
        app.enqueueTask(uploadSelect.getTaskQueue(), new FailRunnable(uploadSelect, uploadIndex, fileName,
                contentType, new UploadSizeLimitExceededException(e), progress));
    } catch (final MultipartStream.MalformedStreamException e) {
        app.enqueueTask(uploadSelect.getTaskQueue(),
                new CancelRunnable(uploadSelect, uploadIndex, fileName, contentType, e, progress));
    }
}

From source file:de.egore911.opengate.FileuploadServletRequest.java

public static FileuploadServletRequest wrap(HttpServletRequest req, User user)
        throws ServletException, IOException {
    if (req.getContentType().toLowerCase(Locale.ENGLISH).startsWith(FileUploadBase.MULTIPART)) {
        Map<String, Object> parameters = new HashMap<String, Object>();
        Map<String, List<String>> parameterValues = new HashMap<String, List<String>>();
        ServletFileUpload upload = new ServletFileUpload();
        try {//from w w w  . j  a  va2 s . c  om
            FileItemIterator iter = upload.getItemIterator(req);
            while (iter.hasNext()) {
                FileItemStream stream = iter.next();
                InputStream s = stream.openStream();
                try {
                    String fieldName = stream.getFieldName();
                    if (stream.isFormField()) {
                        if (parameters.containsKey(fieldName)) {
                            if (!parameterValues.containsKey(fieldName)) {
                                parameterValues.put(fieldName, new ArrayList<String>());
                                parameterValues.get(fieldName).add((String) parameters.get(fieldName));
                            }
                            parameterValues.get(fieldName).add(IOUtils.toString(s));
                        } else {
                            parameters.put(fieldName, IOUtils.toString(s));
                        }
                    } else {
                        byte[] byteArray = IOUtils.toByteArray(s);
                        if (byteArray.length > 0) {
                            BinaryData binaryData = new BinaryData();
                            binaryData.setData(new Blob(byteArray));
                            binaryData.setMimetype(stream.getContentType());
                            binaryData.setFilename(stream.getName());
                            binaryData.setSize(byteArray.length);
                            AbstractEntity.setCreated(binaryData, user);
                            parameters.put(fieldName, binaryData);
                        }
                    }
                } finally {
                    s.close();
                }
            }
        } catch (FileUploadException e) {
            throw new ServletException(e);
        }
        return new FileuploadServletRequest(parameters, parameterValues);
    } else {
        return new FileuploadServletRequest(req);
    }
}

From source file:controllers.UploadController.java

/**
 * //  w  w w .jav  a2s.  c  o  m
 * This upload method expects a file and simply displays the file in the
 * multipart upload again to the user (in the correct mime encoding).
 * 
 * @param context
 * @return
 * @throws Exception
 */
public Result uploadFinish(Context context) throws Exception {

    // we are using a renderable inner class to stream the input again to
    // the user
    Renderable renderable = new Renderable() {

        @Override
        public void render(Context context, Result result) {

            try {
                // make sure the context really is a multipart context...
                if (context.isMultipart()) {

                    // This is the iterator we can use to iterate over the
                    // contents
                    // of the request.
                    FileItemIterator fileItemIterator = context.getFileItemIterator();

                    while (fileItemIterator.hasNext()) {

                        FileItemStream item = fileItemIterator.next();

                        String name = item.getFieldName();
                        InputStream stream = item.openStream();

                        String contentType = item.getContentType();

                        if (contentType != null) {
                            result.contentType(contentType);
                        } else {
                            contentType = mimeTypes.getMimeType(name);
                        }

                        ResponseStreams responseStreams = context.finalizeHeaders(result);

                        if (item.isFormField()) {
                            System.out.println("Form field " + name + " with value " + Streams.asString(stream)
                                    + " detected.");
                        } else {
                            System.out.println(
                                    "File field " + name + " with file name " + item.getName() + " detected.");
                            // Process the input stream

                            ByteStreams.copy(stream, responseStreams.getOutputStream());

                        }
                    }

                }

            } catch (IOException | FileUploadException exception) {

                throw new InternalServerErrorException(exception);

            }

        }
    };

    return new Result(200).render(renderable);

}

From source file:fedora.server.rest.RestUtil.java

/**
 * Retrieves the contents of the HTTP Request.
 * @return InputStream from the request//w  w  w. ja  v  a  2  s.c om
 */
public RequestContent getRequestContent(HttpServletRequest request, HttpHeaders headers) throws Exception {
    RequestContent rContent = null;

    // See if the request is a multi-part file upload request
    if (ServletFileUpload.isMultipartContent(request)) {

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload();

        // Parse the request, use the first available File item
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (!item.isFormField()) {
                rContent = new RequestContent();
                rContent.contentStream = item.openStream();
                rContent.mimeType = item.getContentType();

                FileItemHeaders itemHeaders = item.getHeaders();
                if (itemHeaders != null) {
                    String contentLength = itemHeaders.getHeader("Content-Length");
                    if (contentLength != null) {
                        rContent.size = Integer.parseInt(contentLength);
                    }
                }

                break;
            }
        }
    } else {
        // If the content stream was not been found as a multipart,
        // try to use the stream from the request directly
        if (rContent == null) {
            if (request.getContentLength() > 0) {
                rContent = new RequestContent();
                rContent.contentStream = request.getInputStream();
                rContent.size = request.getContentLength();
            } else {
                String transferEncoding = request.getHeader("Transfer-Encoding");
                if (transferEncoding != null && transferEncoding.contains("chunked")) {
                    BufferedInputStream bis = new BufferedInputStream(request.getInputStream());
                    bis.mark(2);
                    if (bis.read() > 0) {
                        bis.reset();
                        rContent = new RequestContent();
                        rContent.contentStream = bis;
                    }
                }
            }
        }
    }

    // Attempt to set the mime type and size if not already set
    if (rContent != null) {
        if (rContent.mimeType == null) {
            MediaType mediaType = headers.getMediaType();
            if (mediaType != null) {
                rContent.mimeType = mediaType.toString();
            }
        }

        if (rContent.size == 0) {
            List<String> lengthHeaders = headers.getRequestHeader("Content-Length");
            if (lengthHeaders != null && lengthHeaders.size() > 0) {
                rContent.size = Integer.parseInt(lengthHeaders.get(0));
            }
        }
    }

    return rContent;
}

From source file:controllers.PictureController.java

@FilterWith(SecureFilter.class)
public Result uploadFinish(@LoggedInUser String username, Context context) throws Exception {
    String fileLocation = "";
    // Make sure the context really is a multipart context...
    if (context.isMultipart()) {
        Picture pic = new Picture();
        // This is the iterator we can use to iterate over the
        // contents of the request.
        FileItemIterator fileItemIterator = context.getFileItemIterator();

        while (fileItemIterator.hasNext()) {

            FileItemStream item = fileItemIterator.next();

            String name = item.getFieldName();
            InputStream stream = item.openStream();

            String contentType = item.getContentType();

            if (item.isFormField()) {
                String value = Streams.asString(stream);
                switch (name) {
                case "name":
                    pic.setName(value);//from w w w  .  j a va  2  s. c o  m
                    break;
                case "about":
                    pic.setAbout(value);
                    break;
                }

            } else {
                OutputStream outputStream = null;

                try {
                    fileLocation = "public/pictures/" + item.getName();
                    outputStream = new FileOutputStream(new File(fileLocation));

                    int read = 0;
                    byte[] bytes = new byte[1024];

                    while ((read = stream.read(bytes)) != -1) {
                        outputStream.write(bytes, 0, read);
                    }
                    pic.setFile(item.getName());

                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (stream != null) {
                        try {
                            stream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (outputStream != null) {
                        try {
                            // outputStream.flush();
                            outputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }
                }
            }
        }
        pictureDao.postArticlePicture(username, pic);
    }

    reziseImage(fileLocation);
    // We always return ok. You don't want to do that in production ;)
    return Results.redirect("/picture/all");

}

From source file:de.egore911.reader.servlets.OpmlImportServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    User user = getUserOrRedirect(resp);
    if (user == null) {
        return;/*from   w w w . j  av  a2s.  c om*/
    }

    boolean success = false;
    String reason = null;
    ServletFileUpload upload = new ServletFileUpload();
    CategoryDao categoryDao = new CategoryDao();
    FeedUserDao feedUserDao = new FeedUserDao();
    FeedDao feedDao = new FeedDao();
    try {
        FileItemIterator iter = upload.getItemIterator(req);
        // Parse the request
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            if ("subscriptions".equals(name) && !item.isFormField()
                    && "text/xml".equals(item.getContentType())) {
                try (InputStream stream = item.openStream()) {
                    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                    Document document = documentBuilder.parse(stream);

                    document.getDocumentElement().normalize();

                    Element opml = document.getDocumentElement();
                    if (!"opml".equals(opml.getTagName())) {
                        throw new ServletException("Invalid XML");
                    }

                    NodeList nodes = opml.getChildNodes();
                    for (int i = 0; i < nodes.getLength(); i++) {
                        Node node = nodes.item(i);
                        if (node.getNodeType() == Node.ELEMENT_NODE) {
                            Element element = (Element) node;
                            if ("body".equals(element.getTagName())) {
                                if (countFeeds(element.getChildNodes()) < 20) {
                                    importRecursive(categoryDao, feedUserDao, feedDao, user, Category.ROOT,
                                            element.getChildNodes());
                                    success = true;
                                } else {
                                    reason = "to_many_feeds";
                                }
                            }
                        }
                    }

                } catch (ParserConfigurationException | SAXException e) {
                    throw new ServletException(e.getMessage(), e);
                }
            }
        }
    } catch (FileUploadException e) {
        throw new ServletException(e.getMessage(), e);
    }

    if (success) {
        resp.sendRedirect("/reader");
    } else {
        String redirectTo = "/import?msg=import_failed";
        if (reason != null) {
            redirectTo += "&reason=" + reason;
        }
        resp.sendRedirect(redirectTo);
    }
}