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

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

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItem 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.xclinical.mdr.server.DocumentServlet.java

@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    try {/*from   ww w. j  a v a2 s  .  c o  m*/
        if (ServletFileUpload.isMultipartContent(req)) {
            log.debug("detected multipart content");

            final FileInfo info = new FileInfo();

            ServletFileUpload fileUpload = new ServletFileUpload(new DiskFileItemFactory());

            @SuppressWarnings("unchecked")
            List<FileItem> items = fileUpload.parseRequest(req);

            String session = null;

            for (Iterator<FileItem> i = items.iterator(); i.hasNext();) {
                log.debug("detected form field");

                FileItem item = (FileItem) i.next();

                if (item.isFormField()) {
                    String fieldName = item.getFieldName();
                    String fieldValue = item.getString();

                    if (fieldName != null) {
                        log.debug("{0}={1}", fieldName, fieldValue);
                    } else {
                        log.severe("fieldName may not be null");
                    }

                    if ("session".equals(fieldName)) {
                        session = fieldValue;
                    }
                } else {
                    log.debug("detected content");

                    info.contentName = item.getName();
                    info.contentName = new File(info.contentName).getName();
                    info.contentType = item.getContentType();
                    info.content = item.get();

                    log.debug("{0} bytes", info.content.length);
                }
            }

            if (info.content == null)
                throw new IllegalArgumentException("there is no content");
            if (info.contentType == null)
                throw new IllegalArgumentException("There is no content type");
            if (info.contentName == null)
                throw new IllegalArgumentException("There is no content name");

            Session.runInSession(session, new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    Document document = Document.create(info.contentName, info.contentType, info.content);

                    log.info("Created document " + document.getId());

                    ReferenceDocument referenceDocument = saveFile(req, document);

                    JsonCommandServlet.writeResponse(resp, FlatJsonExporter.of(referenceDocument));
                    return null;
                }
            });
        } else {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }

    } catch (FileUploadException e) {
        log.severe(e);
        throw new ServletException(e);
    } catch (Exception e) {
        log.severe(e);
        throw new ServletException(e);
    }
}

From source file:mercury.UploadController.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
        try {//w  w w  .j av a 2  s .  co m
            List items = upload.parseRequest(request);
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (!item.isFormField()) {
                    String targetUrl = Config.getConfigProperty(ConfigurationEnum.DIGITAL_MEDIA);
                    if (StringUtils.isBlank(targetUrl)) {
                        targetUrl = request.getRequestURL().toString();
                        targetUrl = targetUrl.substring(0, targetUrl.lastIndexOf('/'));
                    }
                    targetUrl += "/DigitalMediaController";
                    PostMethod filePost = new PostMethod(targetUrl);
                    filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);
                    UploadPartSource src = new UploadPartSource(item.getName(), item.getSize(),
                            item.getInputStream());
                    Part[] parts = new Part[1];
                    parts[0] = new FilePart(item.getName(), src, item.getContentType(), null);
                    filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
                    HttpClient client = new HttpClient();
                    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
                    int status = client.executeMethod(filePost);
                    if (status == HttpStatus.SC_OK) {
                        String data = filePost.getResponseBodyAsString();
                        JSONObject json = new JSONObject(data);
                        if (json.has("id")) {
                            JSONObject responseJson = new JSONObject();
                            responseJson.put("success", true);
                            responseJson.put("id", json.getString("id"));
                            responseJson.put("uri", targetUrl + "?id=" + json.getString("id"));
                            response.getWriter().write(responseJson.toString());
                        }
                    }
                    filePost.releaseConnection();
                    return;
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (JSONException je) {
            je.printStackTrace();
        }
    }
    response.getWriter().write("{success: false}");
}

From source file:com.uniquesoft.uidl.servlet.UploadServlet.java

private String fileFieldToXml(FileItem i) {
    Map<String, String> item = new HashMap<String, String>();
    item.put(TAG_CTYPE, i.getContentType() != null ? i.getContentType() : "unknown");
    item.put(TAG_SIZE, "" + i.getSize());
    item.put(TAG_NAME, "" + i.getName());
    item.put(TAG_FIELD, "" + i.getFieldName());
    if (i instanceof HasKey) {
        String k = ((HasKey) i).getKeyString();
        item.put(TAG_KEY, k);// ww  w . ja v a  2 s  . c  o m
    }

    Map<String, String> file = new HashMap<String, String>();
    file.put(TAG_FILE, statusToString(item));
    return statusToString(file);
}

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

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

    File dir = ServerContext.getVisUploadDir();
    File uploadedFile = getUniqueName(dir);

    String overrideKey = req.getParameter("cacheKey");

    DiskFileItemFactory factory = new DiskFileItemFactory();

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

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

    // Process the uploaded items
    Iterator iter = items.iterator();
    FileItem item = null;
    if (iter.hasNext()) {
        item = (FileItem) iter.next();//from w w  w .j a  v  a2  s .  c om

        if (!item.isFormField()) {
            try {
                item.write(uploadedFile);
            } catch (Exception e) {
                sendReturnMsg(res, 500, e.getMessage(), null);
                return;
            }

        }
    }

    if (item == null) {
        sendReturnMsg(res, 500, "Could not find a upload file", null);
        return;
    }

    if (FileUtil.isGZipFile(uploadedFile)) {
        File uploadedFileZiped = new File(uploadedFile.getPath() + "." + FileUtil.GZ);
        uploadedFile.renameTo(uploadedFileZiped);
        FileUtil.gUnzipFile(uploadedFileZiped, uploadedFile, (int) FileUtil.MEG);
    }

    PrintWriter resultOut = res.getWriter();
    String retFile = ServerContext.replaceWithPrefix(uploadedFile);
    UploadFileInfo fi = new UploadFileInfo(retFile, uploadedFile, item.getName(), item.getContentType());
    String fileCacheKey = overrideKey != null ? overrideKey : retFile;
    UserCache.getInstance().put(new StringKey(fileCacheKey), fi);
    resultOut.println(fileCacheKey);
    String size = StringUtils.getSizeAsString(uploadedFile.length(), true);
    Logger.info("Successfully uploaded file: " + uploadedFile.getPath(), "Size: " + size);
    Logger.stats(Logger.VIS_LOGGER, "Fits Upload", "fsize", (double) uploadedFile.length() / StringUtils.MEG,
            "bytes", size);
}

From source file:it.univaq.servlet.Upload_rist.java

protected boolean action_upload(HttpServletRequest request) throws FileUploadException, Exception {

    HttpSession s = SecurityLayer.checkSession(request);
    //dichiaro mappe 
    Map rist = new HashMap();
    //prendo id pubblicazione dalla request

    if (ServletFileUpload.isMultipartContent(request)) {
        Map files = new HashMap();
        int idpubb = Integer.parseInt(request.getParameter("id"));
        //La dimensione massima di ogni singolo file su system
        int dimensioneMassimaDelFileScrivibieSulFileSystemInByte = 10 * 1024 * 1024; // 10 MB
        //Dimensione massima della request
        int dimensioneMassimaDellaRequestInByte = 20 * 1024 * 1024; // 20 MB

        // Creo un factory per l'accesso al filesystem
        DiskFileItemFactory factory = new DiskFileItemFactory();

        //Setto la dimensione massima di ogni file, opzionale
        factory.setSizeThreshold(dimensioneMassimaDelFileScrivibieSulFileSystemInByte);

        // Istanzio la classe per l'upload
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Setto la dimensione massima della request
        upload.setSizeMax(dimensioneMassimaDellaRequestInByte);

        // Parso la riquest della servlet, mi viene ritornata una lista di FileItem con
        // tutti i field sia di tipo file che gli altri
        List<FileItem> items = upload.parseRequest(request);

        /*//w  w  w  .j  ava 2s  .com
        * La classe usata non permette di riprendere i singoli campi per
        * nome quindi dovremmo scorrere la lista che ci viene ritornata con
        * il metodo parserequest
        */
        //scorro per tutti i campi inviati
        for (int i = 0; i < items.size(); i++) {
            FileItem item = items.get(i);
            // Controllo se si tratta di un campo di input normale
            if (item.isFormField()) {
                // Prendo solo il nome e il valore
                String name = item.getFieldName();
                String value = item.getString();

                if (name.equals("isbn") || name.equals("editore") || name.equals("lingua")
                        || name.equals("numpagine") || name.equals("datapub")) {
                    rist.put(name, value);
                }

            } // Se si stratta invece di un file
            else {
                // Dopo aver ripreso tutti i dati disponibili name,type,size
                //String fieldName = item.getFieldName();
                String fileName = item.getName();
                String contentType = item.getContentType();
                long sizeInBytes = item.getSize();
                //li salvo nella mappa
                files.put("name", fileName);
                files.put("type", contentType);
                files.put("size", sizeInBytes);
                //li scrivo nel db
                //Database.connect();
                Database.insertRecord("files", files);
                //Database.close();

                // Posso scriverlo direttamente su filesystem
                if (true) {
                    File uploadedFile = new File(
                            getServletContext().getInitParameter("uploads.directory") + fileName);
                    // Solo se veramente ho inviato qualcosa
                    if (item.getSize() > 0) {
                        item.write(uploadedFile);
                    }
                }
                //prendo id del file se  stato inserito
                ResultSet rs1 = Database.selectRecord("files", "name='" + files.get("name") + "'");
                if (!isNull(rs1)) {
                    while (rs1.next()) {
                        rist.put("download", rs1.getInt("id"));
                    }
                }

            }

        }

        rist.put("idpub", idpubb);
        //inserisco dati in tab ristampa
        Database.insertRecord("ristampa", rist);

        return true;
    } else
        return false;
}

From source file:fr.paris.lutece.plugins.calendar.web.CalendarCategoryJspBean.java

/**
 * Create Category/*from   www  .  j  av a 2  s.c  o m*/
 * @param request The HTTP request
 * @return String The url page
 * @throws AccessDeniedException If the user is not allowed to access this
 *             feature
 */
public String doCreateCategory(HttpServletRequest request) throws AccessDeniedException {
    if (!RBACService.isAuthorized(CalendarResourceIdService.RESOURCE_TYPE, RBAC.WILDCARD_RESOURCES_ID,
            CalendarResourceIdService.PERMISSION_MANAGE, getUser())) {
        throw new AccessDeniedException();
    }
    Category category = new Category();
    String strCategoryName = request.getParameter(PARAMETER_CATEGORY_NAME);
    String strCategoryDescription = request.getParameter(PARAMETER_CATEGORY_DESCRIPTION);
    String strWorkgroup = request.getParameter(PARAMETER_WORKGROUP_KEY);

    MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
    FileItem item = mRequest.getFile(PARAMETER_IMAGE_CONTENT);

    // Mandatory field
    if (strCategoryName.length() == 0) {
        return AdminMessageService.getMessageUrl(request, Messages.MANDATORY_FIELDS, AdminMessage.TYPE_STOP);
    }

    Plugin plugin = PluginService.getPlugin(Constants.PLUGIN_NAME);

    // check if category exist
    if (CategoryHome.findByName(strCategoryName, plugin).size() > 0) {
        return AdminMessageService.getMessageUrl(request, MESSAGE_CATEGORY_EXIST, AdminMessage.TYPE_STOP);
    }

    category.setName(strCategoryName);
    category.setDescription(strCategoryDescription);

    byte[] bytes = item.get();

    category.setIconContent(bytes);
    category.setIconMimeType(item.getContentType());
    category.setWorkgroup(strWorkgroup);
    CategoryHome.create(category, plugin);

    return AppPathService.getBaseUrl(request) + JSP_URL_CATEGORY_LIST;
}

From source file:mercury.DigitalMediaDAO.java

public final Integer uploadToDigitalMedia(FileItem file) {
    Connection con = null;/*from w  w  w.  ja v  a  2  s .co m*/
    Integer serial = 0;
    String filename = file.getName();

    if (filename.lastIndexOf('\\') != -1) {
        filename = filename.substring(filename.lastIndexOf('\\') + 1);
    }

    if (filename.lastIndexOf('/') != -1) {
        filename = filename.substring(filename.lastIndexOf('/') + 1);
    }

    try {
        InputStream is = file.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        serial = getNextSerial("digital_media_id_seq");
        if (serial != 0) {
            con = getDataSource().getConnection();
            con.setAutoCommit(false);
            String sql = " INSERT INTO digital_media " + " (id, file, mime_type, file_name) "
                    + " VALUES (?, ?, ?, ?) ";
            PreparedStatement pstm = con.prepareStatement(sql);
            pstm.setInt(1, serial);
            pstm.setBinaryStream(2, bis, (int) file.getSize());
            pstm.setString(3, file.getContentType());
            pstm.setString(4, filename);
            pstm.executeUpdate();
            pstm.close();
            is.close();
            con.commit();
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new DAOException(e.getMessage());
    } finally {
        closeConnection(con);
    }
    return serial;
}

From source file:com.bigdata.rdf.sail.webapp.UpdateServlet.java

private boolean validateItem(final HttpServletResponse resp, final FileItem item) throws IOException {

    final String contentType = item.getContentType();

    if (contentType == null) {

        buildAndCommitResponse(resp, HTTP_BADREQUEST, MIME_TEXT_PLAIN, "Content-Type not specified");

        return false;

    }//from   w w w  .  ja  v a 2  s . c o m

    final RDFFormat format = RDFFormat.forMIMEType(new MiniMime(contentType).getMimeType());

    if (format == null) {

        buildAndCommitResponse(resp, HTTP_BADREQUEST, MIME_TEXT_PLAIN,
                "Content-Type not recognized as RDF: " + contentType);

        return false;

    }

    final RDFParserFactory rdfParserFactory = RDFParserRegistry.getInstance().get(format);

    if (rdfParserFactory == null) {

        buildAndCommitResponse(resp, HTTP_INTERNALERROR, MIME_TEXT_PLAIN,
                "Parser factory not found: Content-Type=" + contentType + ", format=" + format);

        return false;

    }

    if (item.getInputStream() == null) {

        buildAndCommitResponse(resp, HTTP_BADREQUEST, MIME_TEXT_PLAIN, "No content");

        return false;

    }

    return true;

}

From source file:AtualizarUser.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);
    String caminho;//from ww w  .  j ava2  s.c om
    if (isMultipart) {
        try {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = (List<FileItem>) upload.parseRequest(req);
            for (FileItem item : items) {
                if (item.isFormField()) {
                    //                                            items.get(0).getString();
                    req.setAttribute(item.getFieldName(), item.getString());
                    resp.getWriter()
                            .println("No  campo file" + this.getServletContext().getRealPath("/img"));
                    resp.getWriter().println("Name campo: " + item.getFieldName());
                    resp.getWriter().println("Value campo: " + item.getString());

                    req.setAttribute(item.getFieldName(), item.getString());
                } else {
                    //caso seja um campo do tipo file

                    resp.getWriter().println("Campo file");
                    resp.getWriter().println("Name:" + item.getFieldName());
                    resp.getWriter().println("nome arquivo :" + item.getName());
                    resp.getWriter().println("Size:" + item.getSize());
                    resp.getWriter().println("ContentType:" + item.getContentType());
                    if (item.getName() == "" || item.getName() == null) {
                        caminho = "img\\usuario.jpg";
                    } else {
                        caminho = "img" + File.separator + new Date().getTime() + "_" + item.getName();
                        resp.getWriter().println("Caminho: " + caminho);
                        File uploadedFile = new File(
                                "E:\\Documentos\\NetBeansProjects\\SisLivros\\web\\" + caminho);
                        item.write(uploadedFile);

                    }

                    req.setAttribute("caminho", caminho);
                    req.getRequestDispatcher("AtualizarDadosUser").forward(req, resp);
                }

            }
        } catch (Exception e) {
            //            resp.getWriter().println("ocorreu um problema ao fazer o upload: " + e.getMessage());
        }
    }

}

From source file:gwtupload.server.UploadServlet.java

private String fileFieldToXml(FileItem i) {
    Map<String, String> item = new HashMap<String, String>();
    item.put(TAG_CTYPE, i.getContentType() != null ? i.getContentType() : "unknown");
    item.put(TAG_SIZE, "" + i.getSize());
    // CDATA??xml??
    item.put(TAG_NAME, "<![CDATA[" + i.getName() + "]]>");
    item.put(TAG_FIELD, "" + i.getFieldName());
    if (i instanceof HasKey) {
        String k = ((HasKey) i).getKeyString();
        item.put(TAG_KEY, k);/*from  w  w  w  .ja v  a 2  s .c om*/
    }

    Map<String, String> file = new HashMap<String, String>();
    file.put(TAG_FILE, statusToString(item));
    return statusToString(file);
}