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:org.sharegov.cirm.utils.PhotoUploadResource.java

/**
 * Accepts and processes a representation posted to the resource. As
 * response, the content of the uploaded file is sent back the client.
 *//*from w  w w  . j  ava 2s  .co  m*/
@Post
public Representation accept(Representation entity) {
    // NOTE: the return media type here is TEXT_HTML because IE opens up a file download box
    // if it's APPLICATION_JSON as we'd want it.

    Representation rep = new StringRepresentation(GenUtils.ko("Unable to upload, bad request.").toString(),
            MediaType.TEXT_HTML);
    if (entity != null) {
        if (MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) {

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

            // 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();
            //                List<FileItem> items;
            //
            //                // 3/ Request is parsed by the handler which generates a
            //                // list of FileItems

            InputStream is = null;
            Graphics2D g = null;
            FileOutputStream fos = null;
            ByteArrayOutputStream baos = null;

            try {
                FileItemIterator fit = upload.getItemIterator(entity);
                while (fit.hasNext()) {
                    FileItemStream stream = fit.next();
                    if (stream.getFieldName().equals("uploadImage")) {
                        String contentType = stream.getContentType();
                        if (contentType.startsWith("image")) {
                            String extn = contentType.substring(contentType.indexOf("/") + 1);
                            byte[] data = GenUtils.getBytesFromStream(stream.openStream(), true);
                            String filename = "image_" + Refs.idFactory.resolve().newId(null) + "." + extn;
                            //String filename = "srphoto_123" + "."+extn; // + OWLRefs.idFactory.resolve().newId("Photo"); // may add Photo class to ontology
                            File f = new File(StartUp.config.at("workingDir").asString() + "/src/uploaded",
                                    filename);

                            StringBuilder sb = new StringBuilder("");

                            String hostname = java.net.InetAddress.getLocalHost().getHostName();
                            boolean ssl = StartUp.config.is("ssl", true);
                            int port = ssl ? StartUp.config.at("ssl-port").asInteger()
                                    : StartUp.config.at("port").asInteger();
                            if (ssl)
                                sb.append("https://");
                            else
                                sb.append("http://");
                            sb.append(hostname);
                            if ((ssl && port != 443) || (!ssl && port != 80))
                                sb.append(":").append(port);
                            sb.append("/uploaded/");
                            sb.append(filename);

                            //Start : resize Image
                            int rw = 400;
                            int rh = 300;
                            is = new ByteArrayInputStream(data);
                            BufferedImage image = ImageIO.read(is);
                            int w = image.getWidth();
                            int h = image.getHeight();

                            if (w > rw) {
                                BufferedImage bi = new BufferedImage(rw, rh, image.getType());
                                g = bi.createGraphics();
                                g.drawImage(image, 0, 0, rw, rh, null);
                                baos = new ByteArrayOutputStream();
                                ImageIO.write(bi, extn, baos);
                                data = baos.toByteArray();
                            }
                            //End: resize Image

                            fos = new FileOutputStream(f);
                            fos.write(data);

                            Json j = GenUtils.ok().set("image", sb.toString());
                            //Json j = GenUtils.ok().set("image", filename);
                            rep = new StringRepresentation(j.toString(), (MediaType) MediaType.TEXT_HTML);
                        } else {
                            rep = new StringRepresentation(GenUtils.ko("Please upload only Images.").toString(),
                                    MediaType.TEXT_HTML);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            finally {
                if (fos != null) {
                    try {
                        fos.flush();
                        fos.close();
                    } catch (IOException e) {
                    }
                }
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                    }
                }
                if (baos != null) {
                    try {
                        baos.flush();
                        baos.close();
                    } catch (IOException e) {
                    }
                }
                if (g != null) {
                    g.dispose();
                }
            }
        }
    } else {
        // POST request with no entity.
        setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
    }
    return rep;
}

From source file:org.sigmah.server.file.util.MultipartRequest.java

public void parse(MultipartRequestCallback callback)
        throws IOException, FileUploadException, StatusServletException {
    if (!ServletFileUpload.isMultipartContent(request)) {
        LOGGER.error("Request content is not multipart.");
        throw new StatusServletException(Response.SC_PRECONDITION_FAILED);
    }/*ww w. jav a  2  s . com*/

    final FileItemIterator iterator = new ServletFileUpload(new DiskFileItemFactory()).getItemIterator(request);
    while (iterator.hasNext()) {
        // Gets the first HTTP request element.
        final FileItemStream item = iterator.next();

        if (item.isFormField()) {
            final String value = Streams.asString(item.openStream(), "UTF-8");
            properties.put(item.getFieldName(), value);

        } else if (callback != null) {
            callback.onInputStream(item.openStream(), item.getFieldName(), item.getContentType());
        }
    }
}

From source file:org.tangram.components.servlet.ServletRequestParameterAccess.java

/**
 * Weak visibility to avoid direct instanciation.
 *///w  w  w .j a va  2 s  .  c om
@SuppressWarnings("unchecked")
ServletRequestParameterAccess(HttpServletRequest request, long uploadFileMaxSize) {
    final String reqContentType = request.getContentType();
    LOG.debug("() uploadFileMaxSize={} request.contentType={}", uploadFileMaxSize, reqContentType);
    if (StringUtils.isNotBlank(reqContentType) && reqContentType.startsWith("multipart/form-data")) {
        ServletFileUpload upload = new ServletFileUpload();
        upload.setFileSizeMax(uploadFileMaxSize);
        try {
            for (FileItemIterator itemIterator = upload.getItemIterator(request); itemIterator.hasNext();) {
                FileItemStream item = itemIterator.next();
                String fieldName = item.getFieldName();
                InputStream stream = item.openStream();
                if (item.isFormField()) {
                    String[] value = parameterMap.get(item.getFieldName());
                    int i = 0;
                    if (value == null) {
                        value = new String[1];
                    } else {
                        String[] newValue = new String[value.length + 1];
                        System.arraycopy(value, 0, newValue, 0, value.length);
                        i = value.length;
                        value = newValue;
                    } // if
                    value[i] = Streams.asString(stream, "UTF-8");
                    LOG.debug("() request parameter {}='{}'", fieldName, value[0]);
                    parameterMap.put(item.getFieldName(), value);
                } else {
                    try {
                        LOG.debug("() item {} :{}", item.getName(), item.getContentType());
                        final byte[] bytes = IOUtils.toByteArray(stream);
                        if (bytes.length > 0) {
                            originalNames.put(fieldName, item.getName());
                            blobs.put(fieldName, bytes);
                        } // if
                    } catch (IOException ex) {
                        LOG.error("()", ex);
                        if (ex.getCause() instanceof FileUploadBase.FileSizeLimitExceededException) {
                            throw new RuntimeException(ex.getCause().getMessage()); // NOPMD we want to lose parts of our stack trace!
                        } // if
                    } // try/catch
                } // if
            } // for
        } catch (FileUploadException | IOException ex) {
            LOG.error("()", ex);
        } // try/catch
    } else {
        parameterMap = request.getParameterMap();
    } // if
}

From source file:password.pwm.http.PwmRequest.java

public Map<String, FileUploadItem> readFileUploads(final int maxFileSize, final int maxItems)
        throws IOException, ServletException, PwmUnrecoverableException {
    final Map<String, FileUploadItem> returnObj = new LinkedHashMap<>();
    try {/*from   www.j  a v  a  2 s.  c o m*/
        if (ServletFileUpload.isMultipartContent(this.getHttpServletRequest())) {
            final ServletFileUpload upload = new ServletFileUpload();
            final FileItemIterator iter = upload.getItemIterator(this.getHttpServletRequest());
            while (iter.hasNext() && returnObj.size() < maxItems) {
                final FileItemStream item = iter.next();
                final InputStream inputStream = item.openStream();
                final ByteArrayOutputStream baos = new ByteArrayOutputStream();
                final long length = IOUtils.copyLarge(inputStream, baos, 0, maxFileSize + 1);
                if (length > maxFileSize) {
                    final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_UNKNOWN,
                            "upload file size limit exceeded");
                    LOGGER.error(this, errorInformation);
                    respondWithError(errorInformation);
                    return Collections.emptyMap();
                }
                final byte[] outputFile = baos.toByteArray();
                final FileUploadItem fileUploadItem = new FileUploadItem(item.getName(), item.getContentType(),
                        outputFile);
                returnObj.put(item.getFieldName(), fileUploadItem);
            }
        }
    } catch (Exception e) {
        LOGGER.error("error reading file upload: " + e.getMessage());
    }
    return Collections.unmodifiableMap(returnObj);
}

From source file:se.vgregion.portal.innovationsslussen.idea.controller.IdeaViewController.java

/**
 * Upload file action./*from  www  .  jav  a  2 s.c  om*/
 *
 * @param request  the request
 * @param response the response
 * @param model    the model
 * @throws FileUploadException the file upload exception
 */
@ActionMapping(params = "action=uploadFile")
public void uploadFile(ActionRequest request, ActionResponse response, Model model)
        throws FileUploadException, SystemException, PortalException {

    ThemeDisplay themeDisplay = getThemeDisplay(request);
    long scopeGroupId = themeDisplay.getScopeGroupId();
    long userId = themeDisplay.getUserId();

    String urlTitle = request.getParameter("urlTitle");

    String fileType = request.getParameter("fileType");
    boolean publicIdea;
    if (fileType.equals("public")) {
        publicIdea = true;
    } else if (fileType.equals("private")) {
        publicIdea = false;
    } else {
        throw new IllegalArgumentException("Unknown filetype: " + fileType);
    }

    //TODO ondig slagning? Cacha?
    Idea idea = ideaService.findIdeaByUrlTitle(urlTitle);
    //TODO Kan det inte finnas flera med samma titel i olika communities?

    IdeaContentType ideaContentType = publicIdea ? IdeaContentType.IDEA_CONTENT_TYPE_PUBLIC
            : IdeaContentType.IDEA_CONTENT_TYPE_PRIVATE;

    if (!isAllowedToDoAction(request, idea, Action.UPLOAD_FILE, ideaContentType)) {
        sendRedirectToContextRoot(response);
        return;
    }

    boolean mayUploadFile = idea.getUserId() == userId;

    IdeaPermissionChecker ideaPermissionChecker = ideaPermissionCheckerService
            .getIdeaPermissionChecker(scopeGroupId, userId, idea);

    if (!mayUploadFile) {
        if (publicIdea) {
            mayUploadFile = ideaPermissionChecker.isHasPermissionAddDocumentPublic();
        } else {
            mayUploadFile = ideaPermissionChecker.isHasPermissionAddDocumentPrivate();
        }
    }

    if (mayUploadFile) {
        response.setRenderParameter("urlTitle", urlTitle);

        PortletFileUpload p = new PortletFileUpload();

        try {
            FileItemIterator itemIterator = p.getItemIterator(request);

            while (itemIterator.hasNext()) {
                FileItemStream fileItemStream = itemIterator.next();

                if (fileItemStream.getFieldName().equals("file")) {

                    InputStream is = fileItemStream.openStream();
                    BufferedInputStream bis = new BufferedInputStream(is);

                    String fileName = fileItemStream.getName();
                    String contentType = fileItemStream.getContentType();

                    ideaService.uploadFile(idea, publicIdea, fileName, contentType, bis);
                }
            }
        } catch (FileUploadException e) {
            doExceptionStuff(e, response, model);
            return;
        } catch (IOException e) {
            doExceptionStuff(e, response, model);
            return;
        } catch (se.vgregion.service.innovationsslussen.exception.FileUploadException e) {
            doExceptionStuff(e, response, model);
            return;
        } catch (RuntimeException e) {
            Throwable lastCause = Util.getLastCause(e);
            if (lastCause instanceof SQLException) {
                SQLException nextException = ((SQLException) lastCause).getNextException();
                if (nextException != null) {
                    LOGGER.error(nextException.getMessage(), nextException);
                }
            }
        } finally {
            response.setRenderParameter("ideaType", fileType);
        }
    } else {
        throw new FileUploadException("The user is not authorized to upload to this idea instance.");
    }

    response.setRenderParameter("urlTitle", urlTitle);
    response.setRenderParameter("type", fileType);
    response.setRenderParameter("showView", "showIdea");
}

From source file:tech.oleks.pmtalk.PmTalkServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    Order o = new Order();
    ServletFileUpload upload = new ServletFileUpload();
    try {/*from   www  .  j a  va 2s  .com*/
        FileItemIterator it = upload.getItemIterator(req);
        while (it.hasNext()) {
            FileItemStream item = it.next();
            InputStream fieldValue = item.openStream();
            String fieldName = item.getFieldName();
            if ("candidate".equals(fieldName)) {
                String candidate = Streams.asString(fieldValue);
                o.setCandidate(candidate);
            } else if ("staffing".equals(fieldName)) {
                String staffingLink = Streams.asString(fieldValue);
                o.setStaffingLink(staffingLink);
            } else if ("resume".equals(fieldName)) {
                FileUpload resume = new FileUpload();
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                IOUtils.copy(fieldValue, os);
                resume.setStream(new ByteArrayInputStream(os.toByteArray()));
                resume.setContentType(item.getContentType());
                resume.setFileName(item.getName());
                o.setResume(resume);
            }
        }
    } catch (FileUploadException e) {
        e.printStackTrace();
    }

    pmTalkService.minimal(o);
    req.setAttribute("order", o);
    if (o.getErrors() != null) {
        forward("/form.jsp", req, resp);
    } else {
        forward("/created.jsp", req, resp);
    }
}

From source file:zutil.jee.upload.AjaxFileUpload.java

@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    FileUploadListener listener = new FileUploadListener();
    try {/*from  w w w.  j a  v  a  2 s .co m*/
        // Initiate list and HashMap that will contain the data
        HashMap<String, String> fields = new HashMap<String, String>();
        ArrayList<FileItem> files = new ArrayList<FileItem>();

        // Add the listener to the session
        HttpSession session = request.getSession();
        LinkedList<FileUploadListener> list = (LinkedList<FileUploadListener>) session
                .getAttribute(SESSION_FILEUPLOAD_LISTENER);
        if (list == null) {
            list = new LinkedList<FileUploadListener>();
            session.setAttribute(SESSION_FILEUPLOAD_LISTENER, list);
        }
        list.add(listener);

        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();
        if (TEMPFILE_PATH != null)
            factory.setRepository(TEMPFILE_PATH);
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setProgressListener(listener);
        // Set overall request size constraint
        //upload.setSizeMax(yourMaxRequestSize);

        // Parse the request
        FileItemIterator it = upload.getItemIterator(request);
        while (it.hasNext()) {
            FileItemStream item = it.next();
            // Is the file type allowed?
            if (!item.isFormField()
                    && !ALLOWED_EXTENSIONS.contains(FileUtil.getFileExtension(item.getName()).toLowerCase())) {
                String msg = "Filetype '" + FileUtil.getFileExtension(item.getName()) + "' is not allowed!";
                logger.warning(msg);
                listener.setStatus(Status.Error);
                listener.setFileName(item.getName());
                listener.setMessage(msg);
                return;
            }
            listener.setFileName(item.getName());
            FileItem fileItem = factory.createItem(item.getFieldName(), item.getContentType(),
                    item.isFormField(), item.getName());
            // Read the file data
            Streams.copy(item.openStream(), fileItem.getOutputStream(), true);
            if (fileItem instanceof FileItemHeadersSupport) {
                final FileItemHeaders fih = item.getHeaders();
                ((FileItemHeadersSupport) fileItem).setHeaders(fih);
            }

            //Handle the item
            if (fileItem.isFormField()) {
                fields.put(fileItem.getFieldName(), fileItem.getString());
            } else {
                files.add(fileItem);
                logger.info("Recieved file: " + fileItem.getName() + " ("
                        + StringUtil.formatByteSizeToString(fileItem.getSize()) + ")");
            }
        }
        // Process the upload
        listener.setStatus(Status.Processing);
        doUpload(request, response, fields, files);
        // Done
        listener.setStatus(Status.Done);
    } catch (Exception e) {
        logger.log(Level.SEVERE, null, e);
        listener.setStatus(Status.Error);
        listener.setFileName("");
        listener.setMessage(e.getMessage());
    }
}