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.sonicle.webtop.core.app.AbstractEnvironmentService.java

private String findMediaType(FileItemStream fileItem) {
    String mtype = ServletHelper.guessMediaType(fileItem.getName());
    if (!StringUtils.isBlank(mtype))
        return mtype;
    mtype = fileItem.getContentType();
    if (!StringUtils.isBlank(mtype))
        return mtype;
    return "application/octet-stream";
}

From source file:fi.helsinki.lib.simplerest.CommunityLogoResource.java

@Put
public Representation put(Representation logoRepresentation) {
    Context c = null;/*from   w ww .  j a v  a 2 s. com*/
    Community community;
    try {
        c = getAuthenticatedContext();
        community = Community.find(c, this.communityId);
        if (community == null) {
            return errorNotFound(c, "Could not find the community.");
        }
    } catch (SQLException e) {
        return errorInternal(c, e.toString());
    }

    try {
        RestletFileUpload rfu = new RestletFileUpload(new DiskFileItemFactory());
        FileItemIterator iter = rfu.getItemIterator(logoRepresentation);
        if (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (!item.isFormField()) {
                InputStream inputStream = item.openStream();

                community.setLogo(inputStream);
                Bitstream logo = community.getLogo();
                BitstreamFormat bf = BitstreamFormat.findByMIMEType(c, item.getContentType());
                logo.setFormat(bf);
                logo.update();
                community.update();
            }
        }
        c.complete();
    } catch (AuthorizeException ae) {
        return error(c, "Unauthorized", Status.CLIENT_ERROR_UNAUTHORIZED);
    } catch (Exception e) {
        return errorInternal(c, e.toString());
    }

    return successOk("Logo set.");
}

From source file:com.smartgwt.extensions.fileuploader.server.ProjectServlet.java

private void processFiles(HttpServletRequest request, HttpServletResponse response) {
    HashMap<String, String> args = new HashMap<String, String>();
    boolean isGWT = true;
    try {/* w  w  w.j  a  v  a  2  s. co m*/
        if (log.isDebugEnabled())
            log.debug(request.getParameterMap());
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter = upload.getItemIterator(request);
        // pick up parameters first and note actual FileItem
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            if (item.isFormField()) {
                args.put(name, Streams.asString(item.openStream()));
            } else {
                args.put("contentType", item.getContentType());
                String fileName = item.getName();
                int slash = fileName.lastIndexOf("/");
                if (slash < 0)
                    slash = fileName.lastIndexOf("\\");
                if (slash > 0)
                    fileName = fileName.substring(slash + 1);
                args.put("fileName", fileName);
                // upload requests can come from smartGWT (args) or
                // FCKEditor (request)
                String contextName = args.get("context");
                String model = args.get("model");
                String path = args.get("path");
                if (contextName == null) {
                    isGWT = false;
                    contextName = request.getParameter("context");
                    model = request.getParameter("model");
                    path = request.getParameter("path");
                    if (log.isDebugEnabled())
                        log.debug("query=" + request.getQueryString());
                } else if (log.isDebugEnabled())
                    log.debug(args);
                // the following code stores the file based on your parameters
                /*               ProjectContext context = ContextService.get().getContext(
                                     contextName);
                               ProjectState state = (ProjectState) request.getSession()
                                     .getAttribute(contextName);
                               InputStream in = null;
                               try {
                                  in = item.openStream();
                                  state.getFileManager().storeFile(
                context.getModel(model), path + fileName, in);
                               } catch (Exception e) {
                                  e.printStackTrace();
                                  log.error("Fail to upload " + fileName + " to " + path);
                               } finally {
                                  if (in != null)
                                     try {
                in.close();
                                     } catch (Exception e) {
                                     }
                               }
                */
            }
        }
        // TODO: need to handle conversion options and error reporting
        response.setContentType("text/html");
        response.setHeader("Pragma", "No-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-cache");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<body>");
        if (isGWT) {
            out.println("<script type=\"text/javascript\">");
            out.println("if (parent.uploadComplete) parent.uploadComplete('" + args.get("fileName") + "');");
            out.println("</script>");
        } else
            out.println(getEditorResponse());
        out.println("</body>");
        out.println("</html>");
        out.flush();
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

From source file:fi.helsinki.lib.simplerest.CollectionLogoResource.java

@Put
public Representation put(Representation logoRepresentation) {
    Context c = null;//w  w  w .j  ava  2 s.  co  m
    Collection collection;
    try {
        c = getAuthenticatedContext();
        collection = Collection.find(c, this.collectionId);
        if (collection == null) {
            return errorNotFound(c, "Could not find the collection.");
        }
    } catch (SQLException e) {
        return errorInternal(c, e.toString());
    }

    try {
        RestletFileUpload rfu = new RestletFileUpload(new DiskFileItemFactory());
        FileItemIterator iter = rfu.getItemIterator(logoRepresentation);
        if (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (!item.isFormField()) {
                InputStream inputStream = item.openStream();

                collection.setLogo(inputStream);
                Bitstream logo = collection.getLogo();
                BitstreamFormat bf = BitstreamFormat.findByMIMEType(c, item.getContentType());
                logo.setFormat(bf);
                logo.update();
                collection.update();
            }
        }
        c.complete();
    } catch (AuthorizeException ae) {
        return error(c, "Unauthorized", Status.CLIENT_ERROR_UNAUTHORIZED);
    } catch (Exception e) {
        return errorInternal(c, e.toString());
    }

    return successOk("Logo set.");
}

From source file:com.priocept.jcr.server.UploadServlet.java

private void processFiles(HttpServletRequest request, HttpServletResponse response) {
    HashMap<String, String> args = new HashMap<String, String>();
    try {/*from  w  w w  .ja  v  a  2 s. c  o m*/
        if (log.isDebugEnabled())
            log.debug(request.getParameterMap());
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter = upload.getItemIterator(request);
        // pick up parameters first and note actual FileItem
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            if (item.isFormField()) {
                args.put(name, Streams.asString(item.openStream()));
            } else {
                args.put("contentType", item.getContentType());
                String fileName = item.getName();
                int slash = fileName.lastIndexOf("/");
                if (slash < 0)
                    slash = fileName.lastIndexOf("\\");
                if (slash > 0)
                    fileName = fileName.substring(slash + 1);
                args.put("fileName", fileName);

                if (log.isDebugEnabled())
                    log.debug(args);

                InputStream in = null;
                try {
                    in = item.openStream();
                    writeToFile(request.getSession().getId() + "/" + fileName, in, true,
                            request.getSession().getServletContext().getRealPath("/"));
                } catch (Exception e) {
                    //                  e.printStackTrace();
                    log.error("Fail to upload " + fileName);

                    response.setContentType("text/html");
                    response.setHeader("Pragma", "No-cache");
                    response.setDateHeader("Expires", 0);
                    response.setHeader("Cache-Control", "no-cache");
                    PrintWriter out = response.getWriter();
                    out.println("<html>");
                    out.println("<body>");
                    out.println("<script type=\"text/javascript\">");
                    out.println("if (parent.uploadFailed) parent.uploadFailed('"
                            + e.getLocalizedMessage().replaceAll("\'|\"", "") + "');");
                    out.println("</script>");
                    out.println("</body>");
                    out.println("</html>");
                    out.flush();
                    return;
                } finally {
                    if (in != null)
                        try {
                            in.close();
                        } catch (Exception e) {
                        }
                }

            }
        }
        response.setContentType("text/html");
        response.setHeader("Pragma", "No-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-cache");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<body>");
        out.println("<script type=\"text/javascript\">");
        out.println("if (parent.uploadComplete) parent.uploadComplete('" + args.get("fileName") + "');");
        out.println("</script>");
        out.println("</body>");
        out.println("</html>");
        out.flush();
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

From source file:edu.caltech.ipac.firefly.server.servlets.AnyFileUpload.java

protected void processRequest(HttpServletRequest req, HttpServletResponse res) throws Exception {

    String dest = req.getParameter(DEST_PARAM);
    String preload = req.getParameter(PRELOAD_PARAM);
    String overrideCacheKey = req.getParameter(CACHE_KEY);
    String fileType = req.getParameter(FILE_TYPE);

    if (!ServletFileUpload.isMultipartContent(req)) {
        sendReturnMsg(res, 400, "Is not a Multipart request. Request rejected.", "");
    }// ww w  .  j a v  a 2s  .  c o  m
    StopWatch.getInstance().start("Upload File");

    ServletFileUpload upload = new ServletFileUpload();
    FileItemIterator iter = upload.getItemIterator(req);
    while (iter.hasNext()) {
        FileItemStream item = iter.next();

        if (!item.isFormField()) {
            String fileName = item.getName();
            InputStream inStream = new BufferedInputStream(item.openStream(),
                    IpacTableUtil.FILE_IO_BUFFER_SIZE);
            String ext = resolveExt(fileName);
            FileType fType = resolveType(fileType, ext, item.getContentType());
            File destDir = resolveDestDir(dest, fType);
            boolean doPreload = resolvePreload(preload, fType);

            File uf = File.createTempFile("upload_", ext, destDir);
            String rPathInfo = ServerContext.replaceWithPrefix(uf);

            UploadFileInfo fi = new UploadFileInfo(rPathInfo, uf, fileName, item.getContentType());
            String fileCacheKey = overrideCacheKey != null ? overrideCacheKey : rPathInfo;
            UserCache.getInstance().put(new StringKey(fileCacheKey), fi);

            if (doPreload && fType == FileType.FITS) {
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(uf),
                        IpacTableUtil.FILE_IO_BUFFER_SIZE);
                TeeInputStream tee = new TeeInputStream(inStream, bos);
                try {
                    final Fits fits = new Fits(tee);
                    FitsRead[] frAry = FitsRead.createFitsReadArray(fits);
                    FitsCacher.addFitsReadToCache(uf, frAry);
                } finally {
                    FileUtil.silentClose(bos);
                    FileUtil.silentClose(tee);
                }
            } else {
                FileUtil.writeToFile(inStream, uf);
            }
            sendReturnMsg(res, 200, null, fileCacheKey);
            Counters.getInstance().increment(Counters.Category.Upload, fi.getContentType());
            return;
        }
    }
    StopWatch.getInstance().printLog("Upload File");
}

From source file:com.google.dotorg.translation_workflow.servlet.UploadServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, MalformedURLException {
    String rawProjectId = request.getParameter("projectId");
    try {//ww w  . jav  a2  s  .c o  m
        ServletFileUpload upload = new ServletFileUpload();
        upload.setSizeMax(1048576);
        UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();
        Cloud cloud = Cloud.open();

        int projectId = Integer.parseInt(rawProjectId);
        Project project = cloud.getProjectById(projectId);
        TextValidator nameValidator = TextValidator.BRIEF_STRING;
        String invalidRows = "";
        int validRows = 0;

        try {
            FileItemIterator iterator = upload.getItemIterator(request);
            int articlesLength = 0;
            while (iterator.hasNext()) {
                FileItemStream item = iterator.next();
                InputStream in = item.openStream();

                if (item.isFormField()) {
                } else {
                    String fieldName = item.getFieldName();
                    String fileName = item.getName();
                    String contentType = item.getContentType();
                    String fileContents = null;
                    if (!contentType.equalsIgnoreCase("text/csv")) {
                        logger.warning("Invalid filetype upload " + contentType);
                        response.sendRedirect(
                                "/project_overview?project=" + rawProjectId + "&msg=invalid_type");
                    }
                    try {
                        fileContents = IOUtils.toString(in);
                        PersistenceManager pm = cloud.getPersistenceManager();
                        Transaction tx = pm.currentTransaction();
                        tx.begin();
                        String[] lines = fileContents.split("\n");
                        List<Translation> newTranslations = new ArrayList<Translation>();
                        articlesLength = lines.length;
                        validRows = articlesLength;
                        int lineNo = 0;
                        for (String line : lines) {
                            lineNo++;
                            line = line.replaceAll("\",", "\";");
                            line = line.replaceAll("\"", "");
                            String[] fields = line.split(";");
                            String articleName = fields[0].replace("_", " ");
                            articleName = nameValidator.filter(URLDecoder.decode(articleName));
                            try {
                                URL url = new URL(fields[1]);
                                String category = "";
                                String difficulty = "";
                                if (fields.length > 2) {
                                    category = nameValidator.filter(fields[2]);
                                }
                                if (fields.length > 3) {
                                    difficulty = nameValidator.filter(fields[3]);
                                }
                                Translation translation = project.createTranslation(articleName, url.toString(),
                                        category, difficulty);
                                newTranslations.add(translation);
                            } catch (MalformedURLException e) {
                                validRows--;
                                invalidRows = invalidRows + "," + lineNo;
                                logger.warning("Invalid URL : " + fields[1]);

                            }
                        }
                        pm.makePersistentAll(newTranslations);
                        tx.commit();
                    } finally {
                        IOUtils.closeQuietly(in);
                    }

                }
            }
            cloud.close();
            logger.info(validRows + " of " + articlesLength + " articles uploaded from csv to the project "
                    + project.getId() + " by User :" + user.getUserId());
            if (invalidRows.length() > 0) {
                response.sendRedirect(
                        "/project_overview?project=" + rawProjectId + "&_invalid=" + invalidRows.substring(1));
            } else {
                response.sendRedirect("/project_overview?project=" + rawProjectId);
            }
            /*response.sendRedirect("/project_overview?project=" + rawProjectId +
                "&_invalid=" + invalidRows.substring(1));*/
        } catch (SizeLimitExceededException e) {

            logger.warning("Exceeded the maximum size (" + e.getPermittedSize() + ") of the file ("
                    + e.getActualSize() + ")");
            response.sendRedirect("/project_overview?project=" + rawProjectId + "&msg=size_exceeded");
        }
    } catch (Exception ex) {
        logger.info("String " + ex.toString());
        throw new ServletException(ex);

    }
}

From source file:com.serli.chell.framework.upload.FileUploadInfo.java

private FileUploadInfo(FileItemStream fis, String fileName, String charsetEncoding) {
    this.fis = fis;
    this.fileName = fileName;
    this.fieldName = fis.getFieldName();
    this.charsetEncoding = charsetEncoding;
    this.item = null;
    if (fileName == null) {
        this.extension = null;
        this.contentType = null;
        this.size = 0;
    } else {/* w ww. j  av  a 2  s .  c o  m*/
        this.extension = FileUtils.extension(fileName);
        this.contentType = getContentType(fis.getContentType(), extension);
        this.size = Constant.UNSPECIFIED;
    }
}

From source file:ca.nrc.cadc.rest.SyncInput.java

private void processMultiPart(FileItemIterator itemIterator)
        throws FileUploadException, IOException, ResourceNotFoundException {
    while (itemIterator.hasNext()) {
        FileItemStream item = itemIterator.next();
        String name = item.getFieldName();
        InputStream stream = item.openStream();
        if (item.isFormField())
            processParameter(name, new String[] { Streams.asString(stream) });
        else// w  w  w.  j  av a  2s.c o m
            processStream(name, item.getContentType(), stream);
    }
}

From source file:n3phele.backend.RepoProxy.java

@POST
@Path("{id}/upload/{bucket}")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response upload(@PathParam("id") Long id, @PathParam("bucket") String bucket,
        @QueryParam("name") String destination, @QueryParam("expires") long expires,
        @QueryParam("signature") String signature, @Context HttpServletRequest request)
        throws NotFoundException {
    Repository repo = Dao.repository().load(id);
    if (!checkTemporaryCredential(expires, signature, repo.getCredential().decrypt().getSecret(),
            bucket + ":" + destination)) {
        log.severe("Expired temporary authorization");
        throw new NotFoundException();
    }/*from   ww  w .ja  v a  2  s .c o  m*/

    try {
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iterator = upload.getItemIterator(request);
        log.info("FileSizeMax =" + upload.getFileSizeMax() + " SizeMax=" + upload.getSizeMax() + " Encoding "
                + upload.getHeaderEncoding());
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();

            if (item.isFormField()) {
                log.info("FieldName: " + item.getFieldName() + " value:" + Streams.asString(item.openStream()));
            } else {
                InputStream stream = item.openStream();
                log.warning("Got an uploaded file: " + item.getFieldName() + ", name = " + item.getName()
                        + " content " + item.getContentType());
                URI target = CloudStorage.factory().putObject(repo, stream, item.getContentType(), destination);
                Response.created(target).build();
            }
        }
    } catch (Exception e) {
        log.log(Level.WARNING, "Processing error", e);
    }

    return Response.status(Status.REQUEST_ENTITY_TOO_LARGE).build();
}