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.liferay.apio.architect.impl.jaxrs.json.reader.MultipartBodyMessageBodyReader.java

private void _storeFileItem(FileItem fileItem, Consumer<String> valueConsumer,
        Consumer<BinaryFile> fileConsumer) throws IOException {

    if (fileItem.isFormField()) {
        InputStream stream = fileItem.getInputStream();

        valueConsumer.accept(Streams.asString(stream));
    } else {/*w w w .  j a v  a 2  s.c  o m*/
        BinaryFile binaryFile = new BinaryFile(fileItem.getInputStream(), fileItem.getSize(),
                fileItem.getContentType());

        fileConsumer.accept(binaryFile);
    }
}

From source file:com.controller.RecipeImage.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* w w w.  j a  v a2s  .c o m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    //retrieving the path to store image from web.xml
    filePath = getServletContext().getInitParameter("recipeImageStorePath");

    //retrieving the path to display image from web.xml
    fileDisplay = getServletContext().getInitParameter("recipeImageDisplayPath");

    // Check that we have a file upload request
    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    if (!isMultipart) {
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<p>No file uploaded</p>");
        out.println("</body>");
        out.println("</html>");
        return;
    }
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize.
    factory.setRepository(new File("c:\\temp"));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);

    try {
        // Parse the request to get file items.
        List fileItems = upload.parseRequest(request);

        // Process the uploaded file items
        Iterator i = fileItems.iterator();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("1");
        while (i.hasNext()) {
            out.println("2");
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                fileName = fi.getName();
                fileName = randomString(fileName);
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();
                // Write the file
                if (fileName.lastIndexOf("\\") >= 0) {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                } else {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
                }
                fi.write(file);
                out.println("Uploaded Filename: " + fileName + "<br>" + filePath);
            } else {
                out.println("No file");
            }
        }
        out.println("</body>");
        out.println("</html>");

        RecipeBean recipeBean = new RecipeBean();
        RecipeDAO recipeDAO = new RecipeDAO();

        String image = fileDisplay + "" + fileName;
        out.println(image);

        HttpSession session = request.getSession();
        String recipeId = (String) session.getAttribute("recipeId");
        session.removeAttribute("recipeId");
        recipeDAO.addImage(recipeId, image);

        response.sendRedirect("Home");

    } catch (Exception ex) {
        System.out.println(ex);
    }
}

From source file:edu.fullerton.ldvservlet.Upload.java

private int addFile(FileItem item, HashMap<String, String> params, Page vpage, String userName,
        ImageTable imageTable) throws ServletException {
    int ret = 0;//  ww  w.ja v a2s.  com

    String fieldName = item.getFieldName();
    String fileName = item.getName();
    String contentType = item.getContentType();
    boolean isInMemory = item.isInMemory();
    long sizeInBytes = item.getSize();
    if (sizeInBytes >= 100 && !fileName.isEmpty()) {
        Matcher m = fileNumPat.matcher(fieldName);
        if (m.find()) {
            String descriptionName = "desc" + m.group(1);
            String description = params.get(descriptionName);
            description = description == null ? "" : description;
            if (isValid(contentType)) {
                try {
                    byte[] buf = item.get();
                    ByteArrayInputStream bis = new ByteArrayInputStream(buf);
                    int imgId = imageTable.addImg(userName, bis, contentType);
                    if (!description.isEmpty()) {
                        imageTable.addDescription(imgId, description);
                    }
                    ret = imgId;
                    vpage.add("uploaded " + fileName + " - " + description);
                    vpage.addBlankLines(1);
                } catch (IOException | SQLException | NoSuchAlgorithmException ex) {
                    String ermsg = "Error reading data for " + fileName + ex.getClass().getSimpleName() + " "
                            + ex.getLocalizedMessage();
                    vpage.add(ermsg);
                    vpage.addBlankLines(1);
                }
            } else {
                vpage.add(String.format("The file: %1$s has an unsuported mime type: %2$s", fileName,
                        contentType));
                vpage.addBlankLines(1);
            }
        }
    }
    return ret;
}

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

/**
 * Modify Category/*from  w  w w.  j a v  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 doModifyCategory(HttpServletRequest request) throws AccessDeniedException {
    if (!RBACService.isAuthorized(CalendarResourceIdService.RESOURCE_TYPE, RBAC.WILDCARD_RESOURCES_ID,
            CalendarResourceIdService.PERMISSION_MANAGE, getUser())) {
        throw new AccessDeniedException();
    }
    Category category = null;
    String strCategoryName = request.getParameter(PARAMETER_CATEGORY_NAME);
    String strCategoryDescription = request.getParameter(PARAMETER_CATEGORY_DESCRIPTION);
    String strCategoryUpdateIcon = request.getParameter(PARAMETER_CATEGORY_UPDATE_ICON);
    String strWorkgroup = request.getParameter(PARAMETER_WORKGROUP_KEY);

    int nIdCategory = checkCategoryId(request);

    if (nIdCategory == ERROR_ID_CATEGORY) {
        return AdminMessageService.getMessageUrl(request, MESSAGE_CATEGORY_ERROR, AdminMessage.TYPE_ERROR);
    }

    // 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
    Collection<Category> categoriesList = CategoryHome.findByName(strCategoryName, plugin);

    if (!categoriesList.isEmpty() && (categoriesList.iterator().next().getId() != nIdCategory)) {
        return AdminMessageService.getMessageUrl(request, MESSAGE_CATEGORY_EXIST, AdminMessage.TYPE_STOP);
    }

    category = CategoryHome.find(nIdCategory, plugin);
    category.setName(strCategoryName);
    category.setDescription(strCategoryDescription);

    if (strCategoryUpdateIcon != null) {
        MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
        FileItem item = mRequest.getFile(PARAMETER_IMAGE_CONTENT);

        byte[] bytes = item.get();
        category.setIconContent(bytes);
        category.setIconMimeType(item.getContentType());
    }

    category.setWorkgroup(strWorkgroup);

    CategoryHome.update(category, plugin);

    return AppPathService.getBaseUrl(request) + JSP_URL_CATEGORY_LIST;
}

From source file:com.github.ikidou.handler.FormHandler.java

private List<FileEntity> getFileEntities(Map<String, Object> result, List<FileItem> fileItems)
        throws Exception {
    List<FileEntity> fileEntities = new ArrayList<>();

    for (FileItem fileItem : fileItems) {

        if (fileItem.isFormField()) {
            fileItem.getFieldName();/*from   w w w .  j a va 2s.  c  om*/
            result.put(fileItem.getFieldName(), fileItem.getString());
            if (!fileItem.isInMemory()) {
                fileItem.delete();
            }
        } else {
            FileEntity fileEntity = new FileEntity();
            fileEntity.name = fileItem.getName();
            fileEntity.contentType = fileItem.getContentType();
            fileEntity.size = fileItem.getSize();
            fileEntity.readableSize = FileSizeUtil.toReadable(fileItem.getSize());
            fileEntity.savePath = "Data/" + fileEntity.name;
            File file = new File(fileEntity.savePath);
            fileItem.write(file);
            fileEntities.add(fileEntity);
        }

    }

    return fileEntities;
}

From source file:com.javaweb.controller.SuaTinTucServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request//from w w  w .j  av a  2 s  .  c  o m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, ParseException {
    response.setContentType("text/html;charset=UTF-8");
    request.setCharacterEncoding("UTF-8");

    //response.setCharacterEncoding("UTF-8");
    HttpSession session = request.getSession();
    String TieuDe = "", NoiDung = "", ngaydang = "", GhiChu = "", fileName = "";
    int idloaitin = 0, idTK = 0, idtt = 0;

    TintucService tintucservice = new TintucService();

    //File upload
    String folderupload = getServletContext().getInitParameter("file-upload");
    String rootPath = getServletContext().getRealPath("/");
    filePath = rootPath + folderupload;
    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();

    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize.
    factory.setRepository(new File("C:\\Windows\\Temp\\"));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);

    try {
        // Parse the request to get file items.
        List fileItems = upload.parseRequest(request);

        // Process the uploaded file items
        Iterator i = fileItems.iterator();

        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                // Get the uploaded file parameters

                String fieldName = fi.getFieldName();
                fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();

                //change file name
                fileName = FileService.ChangeFileName(fileName);

                // Write the file
                if (fileName.lastIndexOf("\\") >= 0) {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                } else {
                    file = new File(filePath + "/" + fileName.substring(fileName.lastIndexOf("\\") + 1));
                }
                fi.write(file);
                //                    out.println("Uploaded Filename: " + fileName + "<br>");
            }

            if (fi.isFormField()) {
                if (fi.getFieldName().equalsIgnoreCase("TieuDe")) {
                    TieuDe = fi.getString("UTF-8");
                } else if (fi.getFieldName().equalsIgnoreCase("NoiDung")) {
                    NoiDung = fi.getString("UTF-8");
                } else if (fi.getFieldName().equalsIgnoreCase("NgayDang")) {
                    ngaydang = fi.getString("UTF-8");
                } else if (fi.getFieldName().equalsIgnoreCase("GhiChu")) {
                    GhiChu = fi.getString("UTF-8");
                } else if (fi.getFieldName().equalsIgnoreCase("loaitin")) {
                    idloaitin = Integer.parseInt(fi.getString("UTF-8"));
                } else if (fi.getFieldName().equalsIgnoreCase("idtaikhoan")) {
                    idTK = Integer.parseInt(fi.getString("UTF-8"));
                } else if (fi.getFieldName().equalsIgnoreCase("idtt")) {
                    idtt = Integer.parseInt(fi.getString("UTF-8"));
                }
            }
        }

    } catch (Exception ex) {
        System.out.println(ex);
    }

    Date NgayDang = new SimpleDateFormat("yyyy-MM-dd").parse(ngaydang);

    Tintuc tt = tintucservice.GetTintucID(idtt);

    tt.setIdTaiKhoan(idTK);
    tt.setTieuDe(TieuDe);
    tt.setNoiDung(NoiDung);
    tt.setNgayDang(NgayDang);
    tt.setGhiChu(GhiChu);
    if (!fileName.equals("")) {
        if (tt.getImgLink() != null) {
            if (!tt.getImgLink().equals(fileName)) {
                tt.setImgLink(fileName);
            }
        } else {
            tt.setImgLink(fileName);
        }
    }

    boolean rs = tintucservice.InsertTintuc(tt);
    if (rs) {
        session.setAttribute("kiemtra", "1");
        response.sendRedirect("SuaTinTuc.jsp?idTintuc=" + idtt);
    } else {
        session.setAttribute("kiemtra", "0");
        response.sendRedirect("SuaTinTuc.jsp?idTintuc=" + idtt);
    }

    //        try (PrintWriter out = response.getWriter()) {
    //            /* TODO output your page here. You may use following sample code. */
    //            out.println("<!DOCTYPE html>");
    //            out.println("<html>");
    //            out.println("<head>");
    //            out.println("<title>Servlet SuaTinTucServlet</title>");            
    //            out.println("</head>");
    //            out.println("<body>");
    //            out.println("<h1>Servlet SuaTinTucServlet at " + request.getContextPath() + "</h1>");
    //            out.println("</body>");
    //            out.println("</html>");
    //        }
}

From source file:com.exedio.copernica.ItemForm.java

private void save() {
    final ArrayList<SetValue<?>> setValues = new ArrayList<SetValue<?>>();

    for (Iterator<?> i = getFields().iterator(); i.hasNext();) {
        final Field field = (Field) i.next();
        if (field.key instanceof DataField) {
            final DataField attribute = (DataField) field.key;
            final Media media = Media.get(attribute);
            final FileItem fileItem = getParameterFile(attribute.getName());

            if (fileItem != null) {
                String contentType = fileItem.getContentType();
                if (contentType != null) {
                    // fix for MSIE behaviour
                    if ("image/pjpeg".equals(contentType))
                        contentType = "image/jpeg";

                    try {
                        final InputStream data = fileItem.getInputStream();
                        media.set(item, data, contentType);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }//from  ww  w .j  a v a2s  .  c  o  m
                }
            }
        }
        if (field.error == null) {
            final FunctionField<?> attribute = (FunctionField<?>) field.key;
            setValues.add(Cope.mapAndCast(attribute, field.getContent()));
        }
    }
    try {
        item.set(setValues.toArray(new SetValue<?>[setValues.size()]));
    } catch (MandatoryViolationException e) {
        final Field field = getFieldByKey(e.getFeature());
        field.error = "error.notnull:" + e.getFeature().toString();
    } catch (FinalViolationException e) {
        throw new RuntimeException(e);
    } catch (UniqueViolationException e) {
        final Field field = getFieldByKey(e.getFeature().getFields().iterator().next());
        field.error = e.getClass().getName();
    } catch (StringLengthViolationException e) {
        final Field field = getFieldByKey(e.getFeature());
        field.error = e.getClass().getName();
    }
}

From source file:com.estampate.corteI.servlet.servlets.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// ww  w  . j a v  a  2 s. co m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    dirUploadFiles = getServletContext().getRealPath(getServletContext().getInitParameter("dirUploadFiles"));
    HttpSession sesion = request.getSession(true);
    if (ServletFileUpload.isMultipartContent(request)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(new Long(getServletContext().getInitParameter("maxFileSize")).longValue());
        List listUploadFiles = null;
        FileItem item = null;
        try {
            listUploadFiles = upload.parseRequest(request);
            Iterator it = listUploadFiles.iterator();
            while (it.hasNext()) {
                item = (FileItem) it.next();
                if (!item.isFormField()) {
                    if (item.getSize() > 0) {
                        String nombre = item.getName();
                        String tipo = item.getContentType();
                        long tamanio = item.getSize();
                        String extension = nombre.substring(nombre.lastIndexOf("."));

                        sesion.setAttribute("sArNombre", String.valueOf(nombre));
                        sesion.setAttribute("sArTipo", String.valueOf(tipo));
                        sesion.setAttribute("sArExtension", String.valueOf(extension));

                        File archivo = new File(dirUploadFiles, "nombreRequest" + extension);
                        item.write(archivo);
                        if (archivo.exists()) {
                            response.sendRedirect("uploadsave.jsp");
                        } else {
                            sesion.setAttribute("sArError", "Ocurrio un error al subir el archiv o");
                            response.sendRedirect("uploaderror.jsp");
                        }
                    }
                }
            }
        } catch (FileUploadException e) {
            sesion.setAttribute("sArError", String.valueOf(e.getMessage()));
            response.sendRedirect("uploaderror.jsp");
        } catch (Exception e) {
            sesion.setAttribute("sArError", String.valueOf(e.getMessage()));
            response.sendRedirect("uploaderror.jsp");
        }
    }
    out.close();

}

From source file:ch.zhaw.init.walj.projectmanagement.admin.properties.LogoUpload.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    isMultipart = ServletFileUpload.isMultipartContent(request);
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    boolean small = request.getParameter("size").equals("small");

    String message = "";

    if (!isMultipart) {
        message = "<div class=\"row\">" + "<div class=\"small-12 columns\">" + "<div class=\"row\">"
                + "<div class=\"callout alert\">" + "<h5>Upload failed</h5>" + "</div></div>" + "</div></div>";
    }//from  w  ww.  java2s.com

    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize.
    factory.setRepository(new File(this.getServletContext().getRealPath("/") + "img/"));

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setSizeMax(maxFileSize);

    try {
        // Parse the request to get file items.
        List fileItems = upload.parseRequest(request);

        // Process the uploaded file items
        Iterator i = fileItems.iterator();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");

        while (i.hasNext()) {

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

            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                String fileName;
                if (small) {
                    fileName = "logo_small.png";
                } else {
                    fileName = "logo.png";
                }
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();
                filePath = this.getServletContext().getRealPath("/") + "img/" + fileName;
                // Write the file
                file = new File(filePath);
                fi.write(file);
                out.println("Uploaded Filename: " + fileName + "<br>");
            }

        }

        out.println("</body>");
        out.println("</html>");

    } catch (Exception ex) {
        System.out.println(ex);
    }

}

From source file:com.takin.mvc.mvc.server.CommonsMultipartResolver.java

/**
 * Parse the given List of Commons FileItems into a Spring MultipartParsingResult,
 * containing Spring MultipartFile instances and a Map of multipart parameter.
 * @param fileItems the Commons FileIterms to parse
 * @param encoding the encoding to use for form fields
 * @return the Spring MultipartParsingResult
 * @see CommonsMultipartFile#CommonsMultipartFile(org.apache.commons.fileupload.FileItem)
 *///from w  w  w  .  j av a 2  s . c o m
protected MultipartParsingResult parseFileItems(List<FileItem> fileItems, String encoding) {
    MultiValueMap<String, CommonsMultipartFile> multipartFiles = new LinkedMultiValueMap<String, CommonsMultipartFile>();
    Map<String, String[]> multipartParameters = new HashMap<String, String[]>();

    // Extract multipart files and multipart parameters.
    for (FileItem fileItem : fileItems) {
        if (fileItem.isFormField()) {
            String value;
            String partEncoding = determineEncoding(fileItem.getContentType(), encoding);
            if (partEncoding != null) {
                try {
                    value = fileItem.getString(partEncoding);
                } catch (UnsupportedEncodingException ex) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("Could not decode multipart item '" + fileItem.getFieldName()
                                + "' with encoding '" + partEncoding + "': using platform default");
                    }
                    value = fileItem.getString();
                }
            } else {
                value = fileItem.getString();
            }
            String[] curParam = multipartParameters.get(fileItem.getFieldName());
            if (curParam == null) {
                // simple form field
                multipartParameters.put(fileItem.getFieldName(), new String[] { value });
            } else {
                // array of simple form fields
                String[] newParam = StringUtils.addStringToArray(curParam, value);
                multipartParameters.put(fileItem.getFieldName(), newParam);
            }
        } else {
            // multipart file field
            CommonsMultipartFile file = new CommonsMultipartFile(fileItem);
            multipartFiles.add(file.getName(), file);
            if (logger.isDebugEnabled()) {
                logger.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize()
                        + " bytes with original filename [" + file.getOriginalFilename() + "], stored "
                        + file.getStorageDescription());
            }
        }
    }
    return new MultipartParsingResult(multipartFiles, multipartParameters);
}