Example usage for org.apache.commons.fileupload.servlet ServletFileUpload ServletFileUpload

List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload ServletFileUpload

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.servlet ServletFileUpload ServletFileUpload.

Prototype

public ServletFileUpload(FileItemFactory fileItemFactory) 

Source Link

Document

Constructs an instance of this class which uses the supplied factory to create FileItem instances.

Usage

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

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request/*from   ww  w .j  a  v  a  2  s  . c om*/
 * @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();
    //        session.removeAttribute("errorreg");
    String TieuDe = "", NoiDung = "", ngaydang = "", GhiChu = "", fileName = "";
    int idloaitin = 0, idTK = 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"));
                }
            }
        }

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

    Date NgayDang = new SimpleDateFormat("yyyy-MM-dd").parse(ngaydang);
    Tintuc tintuc = new Tintuc(idloaitin, idTK, fileName, TieuDe, NoiDung, NgayDang, GhiChu);

    boolean rs = tintucservice.InsertTintuc(tintuc);
    if (rs) {
        session.setAttribute("kiemtra", "1");
        String url = "ThemTinTuc.jsp";
        response.sendRedirect(url);
    } else {
        session.setAttribute("kiemtra", "0");
        String url = "ThemTinTuc.jsp";
        response.sendRedirect(url);
    }

    //        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 ThemTinTucServlet</title>");            
    //            out.println("</head>");
    //            out.println("<body>");
    //            out.println("<h1>Servlet ThemTinTucServlet at " + request.getContextPath() + "</h1>");
    //            out.println("</body>");
    //            out.println("</html>");
    //        }
}

From source file:mml.handler.post.MMLPostHTMLHandler.java

void parseRequest(HttpServletRequest request) throws FileUploadException, Exception {
    if (ServletFileUpload.isMultipartContent(request)) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding(encoding);
        List<FileItem> items = upload.parseRequest(request);
        for (int i = 0; i < items.size(); i++) {
            FileItem item = (FileItem) items.get(i);
            if (item.isFormField()) {
                String fieldName = item.getFieldName();
                if (fieldName != null) {
                    String contents = item.getString(encoding);
                    if (fieldName.equals(Params.DOCID))
                        this.docid = contents;
                    else if (fieldName.equals(Params.DIALECT)) {
                        JSONObject jv = (JSONObject) JSONValue.parse(contents);
                        if (jv.get("language") != null)
                            this.langCode = (String) jv.get("language");
                        this.dialect = jv;
                    } else if (fieldName.equals(Params.HTML)) {
                        html = contents;
                    } else if (fieldName.equals(Params.ENCODING))
                        encoding = contents;
                    else if (fieldName.equals(Params.AUTHOR))
                        author = contents;
                    else if (fieldName.equals(Params.TITLE))
                        title = contents;
                    else if (fieldName.equals(Params.STYLE))
                        style = contents;
                    else if (fieldName.equals(Params.FORMAT))
                        format = contents;
                    else if (fieldName.equals(Params.SECTION))
                        section = contents;
                    else if (fieldName.equals(Params.VERSION1))
                        version1 = contents;
                    else if (fieldName.equals(Params.DESCRIPTION))
                        description = contents;
                }/*ww  w  . j a  v  a2s.c  o  m*/
            }
            // we're not uploading files
        }
        if (encoding == null)
            encoding = "UTF-8";
        if (author == null)
            author = "Anon";
        if (style == null)
            style = "TEI/default";
        if (format == null)
            format = "MVD/TEXT";
        if (section == null)
            section = "";
        if (version1 == null)
            version1 = "/Base/first";
        if (description == null)
            description = "Version " + version1;
        if (docid == null)
            throw new Exception("missing docid");
        if (html == null)
            throw new Exception("Missing html");
        if (dialect == null)
            throw new Exception("Missing dialect");
    }
}

From source file:Controlador.Contr_Evento.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* w w w .ja v  a2 s . c  om*/
 *
 * @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 {
    /*Se detalla el contenido que tendra el servlet*/
    response.setContentType("text/html;charset=UTF-8");
    request.setCharacterEncoding("UTF-8");
    /*Se crea una variable para la sesion*/
    HttpSession session = request.getSession(true);

    boolean b;
    try {
        /*Se declaran las variables necesarias*/
        Cls_Evento eve = new Cls_Evento();
        Cls_Mensajeria sms = new Cls_Mensajeria();
        String Codigo = "", Mensaje = "", Nombre = "", Tipo = "", Imagen = "", url, Peti;
        String urlsalidaimg;
        urlsalidaimg = "/media/santiago/Santiago/IMGTE/";
        //urlsalidaimg = "I:\\IMGTE\\";
        String urlimgservidor = this.getServletContext().getRealPath("/Libs/Customs/images/Evento");

        /*FileItemFactory es una interfaz para crear FileItem*/
        FileItemFactory file_factory = new DiskFileItemFactory();

        /*ServletFileUpload esta clase convierte los input file a FileItem*/
        ServletFileUpload servlet_up = new ServletFileUpload(file_factory);
        /*sacando los FileItem del ServletFileUpload en una lista */

        List items = servlet_up.parseRequest(request);
        Iterator it = items.iterator();

        /*Se evalua cada una de las posibles peticiones y los posibles campos que envien*/
        while (it.hasNext()) {
            FileItem item = (FileItem) it.next();
            if (item.isFormField()) {
                //Plain request parameters will come here. 

                String name = item.getFieldName();
                if (name.equals("Creador")) {
                    /*Se guarda el campo en la clase*/
                    eve.setCreador(item.getString());
                } else if (name.equals("Nombre")) {
                    /*Se guarda el campo en la clase*/
                    eve.setNombre(item.getString());
                } else if (name.equals("Codigo")) {
                    /*Se guarda el campo en la clase*/
                    eve.setCodigo(item.getString());
                } else if (name.equals("Rango")) {
                    /*Se guarda el campo en la clase*/
                    eve.setRango(item.getString());
                } else if (name.equals("Rangomaximo")) {
                    /*Se guarda el campo en la clase*/
                    eve.setRangoMaximo(item.getString());
                } else if (name.equals("Fecha")) {
                    /*Se guarda el campo en la clase*/
                    eve.setFecha(item.getString());
                } else if (name.equals("Descripcion")) {
                    /*Se guarda el campo en la clase*/
                    eve.setDescipcion(item.getString());
                } else if (name.equals("Ciudad")) {
                    /*Se guarda el campo en la clase*/
                    eve.setCiudad(item.getString());
                } else if (name.equals("Direccion")) {
                    /*Se guarda el campo en la clase*/
                    eve.setDireccion(item.getString());
                } else if (name.equals("Motivo")) {
                    /*Se guarda el campo en la clase*/
                    eve.setMotivo(item.getString());
                } else if (name.equals("Latitud")) {
                    /*Se guarda el campo en la clase*/
                    eve.setLatitud(item.getString());
                } else if (name.equals("Longitud")) {
                    /*Se guarda el campo en la clase*/
                    eve.setLongitud(item.getString());
                } else if (name.equals("RegistrarEvento")) {
                    /*Se convierte la fecha a date*/
                    if (eve.ConvertirFecha(eve.getFecha())) {
                        /*Se evalua si la fecha tiene dos dias mas a la fecha de hoy*/
                        if (eve.ValidarDosDiasFecha(eve.getFechaDate())) {
                            /*Se evalua si se mando una iamgen*/
                            if (!eve.getImagen().equals("")) {
                                /*Si se envia una imagen obtiene la imagen para eliminarla luego*/
                                File img = new File(eve.getImagen());
                                /*Se ejecuta el metodo de registrar evento, en la clase modelo
                                 con los datos que se encuentran en la clase*/
                                String rangoprecios = eve.getRango() + "-" + eve.getRangoMaximo();
                                b = eve.setRegistrarEvento(eve.getTypeimg(), eve.getNombre(),
                                        eve.getFechaDate(), eve.getDescipcion(), rangoprecios, eve.getCreador(),
                                        eve.getCiudad(), eve.getDireccion(), eve.getLatitud(),
                                        eve.getLongitud());
                                if (b) {
                                    File imagedb = new File(
                                            urlimgservidor + "/" + eve.getCodigo() + eve.getTypeimg());
                                    img.renameTo(imagedb);
                                    /*Se guarda un mensaje mediante las sesiones
                                     y se redirecciona*/
                                    session.setAttribute("Mensaje",
                                            "Se registro el evento satisfactoriamente.");
                                    session.setAttribute("TipoMensaje", "Dio");
                                    response.sendRedirect(
                                            "View/RClasificacionEvento.jsp?CodigoEvento=" + eve.getCodigo());
                                } else {
                                    img.delete();
                                    /*Se guarda un mensaje mediante las sesiones
                                     y se redirecciona*/
                                    session.setAttribute("Mensaje", eve.getMensaje());
                                    session.setAttribute("TipoMensaje", "NODio");
                                    response.sendRedirect("View/RegistrarEvento.jsp");
                                }
                            } else {
                                /*Se guarda un mensaje mediante las sesiones
                                 y se redirecciona*/
                                session.setAttribute("Mensaje",
                                        "Seleccione una imagen para registrar el evento");
                                session.setAttribute("TipoMensaje", "NODio");
                                response.sendRedirect("View/RegistrarEvento.jsp");
                            }

                        } else {
                            /*Se guarda un mensaje mediante las sesiones
                             y se redirecciona*/
                            session.setAttribute("Mensaje",
                                    "No se puede registrar un evento que inicie antes de dos das");
                            session.setAttribute("TipoMensaje", "NODio");
                            response.sendRedirect("View/RegistrarEvento.jsp");
                        }
                    } else {
                        /*Se guarda un mensaje mediante las sesiones
                         y se redirecciona*/
                        session.setAttribute("Mensaje",
                                "Ocurri un problema inesperado con la fecha del evento. Estamos trabajando para solucionar este problema.");
                        session.setAttribute("TipoMensaje", "NODio");
                        response.sendRedirect("View/RegistrarEvento.jsp");
                    }

                } else if (name.equals("DesactivarEvento")) {
                    if (eve.validar_Cancelar_Evento_Un_Dia(eve.getCodigo())) {
                        /*Se ejecuta el metodo de desaprobar evento, en la clase modelo
                         con los datos que se encuentran en la clase*/
                        if (eve.setDesaprobarEvento(eve.getCodigo(), eve.getMotivo())) {
                            String[] Datos = eve.BuscarEventoParaMensaje(eve.getCodigo());
                            if (sms.EnviarMensajeCambioEstadoEvento(Datos, "Desaprobado", eve.getMotivo())) {
                                /*Se guarda un mensaje mediante las sesiones
                                 y se redirecciona*/
                                session.setAttribute("Mensaje", "Se cancel el evento satisfactoriamente.");
                                session.setAttribute("TipoMensaje", "Dio");
                            } else {
                                /*Se guarda un mensaje mediante las sesiones
                                 y se redirecciona*/
                                session.setAttribute("Mensaje",
                                        "Se cancel el evento, pero no se logr enviar la notificacin al correo electrnico de la empresa.");
                                session.setAttribute("TipoMensaje", "NODio");
                            }
                        } else {
                            /*Se guarda un mensaje mediante las sesiones
                             y se redirecciona*/
                            session.setAttribute("Mensaje",
                                    "Ocurri un error al cancelar el evento. Estamos trabajando para solucionar este problema.");
                            session.setAttribute("TipoMensaje", "NODio");
                        }
                    } else {
                        session.setAttribute("Mensaje",
                                "No se puede cancelar un evento antes de un da de su inicio. Lo lamentamos.");
                        session.setAttribute("TipoMensaje", "NODio");
                    }
                    response.sendRedirect("View/CEventoPendiente.jsp");
                } else if (name.equals("DesactivarEventoAdmin")) {
                    if (eve.validar_Cancelar_Evento_Un_Dia(eve.getCodigo())) {
                        /*Se ejecuta el metodo de desaprobar evento, en la clase modelo
                         con los datos que se encuentran en la clase(administradir)*/
                        if (eve.setDesaprobarEvento(eve.getCodigo(), eve.getMotivo())) {
                            String[] Datos = eve.BuscarEventoParaMensaje(eve.getCodigo());
                            if (sms.EnviarMensajeCambioEstadoEvento(Datos, "Desaprobado", eve.getMotivo())) {
                                /*Se guarda un mensaje mediante las sesiones
                                 y se redirecciona*/
                                session.setAttribute("Mensaje", "Se desaprob el evento satisfactoriamente.");
                                session.setAttribute("TipoMensaje", "Dio");
                            } else {
                                /*Se guarda un mensaje mediante las sesiones
                                 y se redirecciona*/
                                session.setAttribute("Mensaje",
                                        "Se desaprob el evento, pero no se logr enviar la notificacin al correo electrnico de la empresa.");
                                session.setAttribute("TipoMensaje", "NODio");
                            }
                        } else {
                            /*Se guarda un mensaje mediante las sesiones
                             y se redirecciona*/
                            session.setAttribute("Mensaje",
                                    "Ocurri un error al desaprobar el evento. Estamos trabajando para solucionar este problema.");
                            session.setAttribute("TipoMensaje", "NODio");
                        }
                    } else {
                        session.setAttribute("Mensaje",
                                "No se puede cancelar un evento antes de un da de su inicio. Lo lamentamos.");
                        session.setAttribute("TipoMensaje", "NODio");
                    }
                    response.sendRedirect("View/ConsultaTodosEventos.jsp");
                } else if (name.equals("DesactivarEventoEmpresa")) {
                    if (eve.validar_Cancelar_Evento_Un_Dia(eve.getCodigo())) {
                        /*Se ejecuta el metodo de desaprobar evento, en la clase modelo
                         con los datos que se encuentran en la clase(Empresa)*/
                        if (eve.setCancelarEvento(eve.getCodigo(), eve.getMotivo())) {
                            session.setAttribute("Mensaje", "Se cancel el evento satisfactoriamente.");
                            session.setAttribute("TipoMensaje", "Dio");
                        } else {
                            session.setAttribute("Mensaje",
                                    "Ocurri un error al cancelar el evento. Estamos trabajando para solucionar este problema.");
                            session.setAttribute("TipoMensaje", "NODio");
                        }

                    } else {
                        session.setAttribute("Mensaje",
                                "No se puede cancelar un evento antes de un da de su inicio. Lo lamentamos.");
                        session.setAttribute("TipoMensaje", "NODio");
                    }
                    response.sendRedirect("View/MisEventos.jsp");
                }

            } else {
                if (!item.getName().equals("")) {
                    //uploaded files will come here.
                    FileItem file = item;
                    String fieldName = item.getFieldName();
                    String fileName = item.getName();
                    String contentType = item.getContentType();
                    boolean isInMemory = item.isInMemory();
                    long sizeInBytes = item.getSize();

                    if (sizeInBytes > 1000000) {
                        /*Se muestra un mensaje en caso de pesar mas de 3 MB*/
                        session.setAttribute("Mensaje", "El tamao lmite de la imagen es: 1 MB");
                        session.setAttribute("TipoMensaje", "NODio");
                        /*Se redirecciona*/
                        response.sendRedirect("View/ConsultaSeleccion.jsp");
                    } else {
                        if (contentType.indexOf("jpeg") > 0 || contentType.indexOf("png") > 0) {
                            if (contentType.indexOf("jpeg") > 0) {
                                contentType = ".jpg";
                            } else {
                                contentType = ".png";
                            }
                            /*Se crea la imagne*/
                            File archivo_server = new File(urlimgservidor + "/" + item.getName());
                            /*Se guardael url de la imagen en la clase*/
                            eve.setImagen(urlimgservidor + "/" + item.getName());
                            eve.setTypeimg(contentType);
                            /*Se guarda la imagen*/
                            item.write(archivo_server);
                        } else {
                            session.setAttribute("Mensaje", "Solo se pueden registrar imagenes JPG o PNG");
                            session.setAttribute("TipoMensaje", "NODio");
                        }
                    }
                } else {
                    /**
                     * Se guardael url de la imagen en la clase
                     */
                    eve.setImagen("");
                }
            }
        }

        response.sendRedirect("View/index.jsp");
    } catch (FileUploadException ex) {
        System.out.print(ex.getMessage().toString());

    } catch (Exception ex) {
        Logger.getLogger(Contr_Seleccion.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:admin.controller.ServletEditCategories.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w w  w .  j av a2 s  .  com
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.processRequest(request, response);
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;
    try {

        upload_path = AppConstants.ORG_CATEGORIES_HOME;

        // Verify the content type
        String contentType = request.getContentType();
        if ((contentType.indexOf("multipart/form-data") >= 0)) {

            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(AppConstants.TMP_FOLDER));

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

            // 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>JSP File upload</title>");
            out.println("</head>");
            out.println("<body>");
            while (i.hasNext()) {
                FileItem fi = (FileItem) i.next();
                if (fi.isFormField()) {
                    // Get the uploaded file parameters
                    field_name = fi.getFieldName();
                    if (field_name.equals("category_name")) {
                        category_name = fi.getString();
                    }
                    if (field_name.equals("category_id")) {
                        category_id = fi.getString();
                    }
                    if (field_name.equals("organization")) {
                        organization_id = fi.getString();
                        upload_path = upload_path + File.separator + organization_id;
                    }

                } else {
                    field_name = fi.getFieldName();
                    file_name = fi.getName();

                    if (file_name != "") {
                        File uploadDir = new File(upload_path);
                        if (!uploadDir.exists()) {
                            uploadDir.mkdirs();
                        }

                        //                            int inStr = file_name.indexOf(".");
                        //                            String Str = file_name.substring(0, inStr);
                        //
                        //                            file_name = category_name + "_" + Str + ".jpeg";
                        file_name = category_name + "_" + file_name;
                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();

                        String filePath = upload_path + File.separator + file_name;
                        File storeFile = new File(filePath);

                        fi.write(storeFile);

                        out.println("Uploaded Filename: " + filePath + "<br>");
                    }
                }
            }
            categories.editCategories(Integer.parseInt(category_id), Integer.parseInt(organization_id),
                    category_name, file_name);
            response.sendRedirect(request.getContextPath() + "/admin/categories.jsp");
            out.println("</body>");
            out.println("</html>");
        } else {
            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>");
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Exception while editing categories", ex);
    } finally {
        try {
            out.close();
        } catch (Exception e) {
        }
    }

}

From source file:admin.controller.ServletUploadFonts.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   ww w  .j  av  a  2  s .  c om
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    super.processRequest(request, response);
    response.setContentType("text/html;charset=UTF-8");
    String filePath;
    String file_name = null, field_name, upload_path;
    RequestDispatcher request_dispatcher;
    String font_name = "", look_id;
    String font_family_name = "";
    PrintWriter out = response.getWriter();
    File file;
    int maxFileSize = 5000 * 1024;
    int maxMemSize = 5000 * 1024;

    try {

        // Verify the content type
        String contentType = request.getContentType();
        if ((contentType.indexOf("multipart/form-data") >= 0)) {

            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(AppConstants.TMP_FOLDER));

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

            // 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
                    field_name = fi.getFieldName();
                    if (field_name.equals("fontname")) {
                        font_name = fi.getString();
                    }
                    if (field_name.equals("fontstylecss")) {
                        font_family_name = fi.getString();
                    }

                } else {

                    //                        check = fonts.checkAvailability(font_name);
                    //                        if (check == false){

                    field_name = fi.getFieldName();
                    file_name = fi.getName();

                    if (file_name != "") {
                        File uploadDir = new File(AppConstants.BASE_FONT_UPLOAD_PATH);
                        if (!uploadDir.exists()) {
                            uploadDir.mkdirs();
                        }

                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();

                        filePath = AppConstants.BASE_FONT_UPLOAD_PATH + File.separator + file_name;
                        File storeFile = new File(filePath);

                        fi.write(storeFile);

                        out.println("Uploaded Filename: " + filePath + "<br>");
                    }
                    fonts.addFont(font_name, file_name, font_family_name);
                    response.sendRedirect(request.getContextPath() + "/admin/fontsfamily.jsp");

                    //                            }else {
                    //                                response.sendRedirect(request.getContextPath() + "/admin/fontsfamily.jsp?exist=exist");
                    //                            }
                }
            }
        }

    } catch (Exception e) {
        logger.log(Level.SEVERE, "Exception while uploading fonts", e);
    }
}

From source file:com.utilities.FileManager.java

public FileManager(ServletContext servletContext, HttpServletRequest request) {
    // get document root like in php
    String contextPath = request.getContextPath();
    String documentRoot = servletContext.getRealPath("/").replaceAll("\\\\", "/");
    System.out.println("CP: " + contextPath + " DR: " + documentRoot);
    //documentRoot = documentRoot.substring(0, documentRoot.indexOf(contextPath));

    this.referer = request.getHeader("referer");
    System.out.println("Referer: " + this.referer);
    this.fileManagerRoot = documentRoot; //+ referer.substring(referer.indexOf(contextPath), referer.indexOf("fileManager.jsp"));

    // get uploaded file list
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    if (ServletFileUpload.isMultipartContent(request))
        try {//from  w  ww  .j av a2s .co  m
            files = upload.parseRequest(request);
        } catch (Exception e) { // no error handling}
        }

    this.properties.put("Date Created", null);
    this.properties.put("Date Modified", null);
    this.properties.put("Height", null);
    this.properties.put("Width", null);
    this.properties.put("Size", null);

    // load config file
    loadConfig();

    if (config.getProperty("doc_root") != null)
        this.documentRoot = config.getProperty("doc_root");
    else
        this.documentRoot = documentRoot;

    dateFormat = new SimpleDateFormat(config.getProperty("date"));

    this.setParams();

    loadLanguageFile();
}

From source file:br.edu.ifpb.ads.psd.projeto.servlets.UploadImagemPerfil.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from   w  ww . j a v a 2 s . co  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Usuario usuario = ((Usuario) request.getSession().getAttribute("usuario"));
    if (usuario == null) {
        response.sendRedirect("");
    } else {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = null;
            try {
                items = (List<FileItem>) upload.parseRequest(request);
            } catch (FileUploadException ex) {
                Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex);
            }
            FileItem item = items.get(0);
            if (item != null) {
                String nome_arquivo = String.valueOf(new Date().getTime()) + item.getName();
                String caminho = getServletContext().getRealPath("/imagens") + "\\" + usuario.getId() + "\\";
                File file = new File(caminho);
                if (!file.exists()) {
                    file.mkdirs();
                }
                File uploadedFile = new File(caminho + nome_arquivo);
                try {
                    item.write(uploadedFile);
                } catch (Exception ex) {
                    Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex);
                }
                GerenciadorDeUsuario gerenciarUsuario = new GerenciadorDeUsuario();
                try {
                    gerenciarUsuario.atualizarFotoPerfil("imagens" + "/" + usuario.getId() + "/" + nome_arquivo,
                            usuario.getId());
                } catch (SQLException ex) {
                    Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex);
                }
                GerenciarFotos gerenciarFotos = new GerenciarFotos();
                try {
                    gerenciarFotos.publicarFoto("imagens" + "/" + usuario.getId() + "/" + nome_arquivo,
                            usuario);
                } catch (SQLException ex) {
                    Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex);
                }
                try {
                    usuario = gerenciarUsuario.getUsuario(usuario.getId());
                } catch (SQLException ex) {
                    Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex);
                }
                request.getSession().setAttribute("usuario", usuario);
                response.sendRedirect("configuracao");
            } else {

            }
        }

    }
}

From source file:it.eng.spagobi.engines.talend.services.JobUploadService.java

public void doService(EngineStartServletIOManager servletIOManager) throws SpagoBIEngineException {

    boolean isMultipart;
    FileItemFactory factory;//from   ww w. j  a v a2 s  .  c  o m
    ServletFileUpload upload;
    JobDeploymentDescriptor jobDeploymentDescriptor;

    logger.debug("IN");

    try {

        auditServiceStartEvent();

        //  Check that we have a file upload request
        isMultipart = ServletFileUpload.isMultipartContent(servletIOManager.getRequest());

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

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

        // Parse the request
        List items = null;
        try {
            items = upload.parseRequest(servletIOManager.getRequest());
        } catch (FileUploadException e) {
            throw new SpagoBIEngineException("Impossible to upload file", "impossible.to.upload.file", e);
        }

        jobDeploymentDescriptor = getJobsDeploymetDescriptor(items);

        // Process the uploaded items
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()) {
                processFormField(item);
            } else {
                String[] jobNames = processUploadedFile(item, jobDeploymentDescriptor);
                if (TalendEngine.getConfig().isAutoPublishActive()) {
                    if (jobNames == null)
                        continue;
                    for (int i = 0; i < jobNames.length; i++) {
                        publishOnSpagoBI(servletIOManager, jobDeploymentDescriptor.getLanguage(),
                                jobDeploymentDescriptor.getProject(), jobNames[i]);
                    }
                }
            }
        }

        servletIOManager.tryToWriteBackToClient("OK");

    } catch (Exception e) {
        throw new SpagoBIEngineException("An error occurred while executing [JobUploadService]",
                "an.unpredicted.error.occured", e);
    } finally {
        logger.debug("OUT");
    }
}

From source file:com.siberhus.web.ckeditor.servlet.MultipartServletRequest.java

public MultipartServletRequest(HttpServletRequest request) throws FileUploadException {
    super(request);

    //      if(!"POST".equals(request.getMethod())){
    //         return;
    //      }//  www . jav a  2s .c o m
    CkeditorConfig config = CkeditorConfigurationHolder.config();
    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // Set factory constraints
    if (config.fileupload().sizeThreshold() != null) {
        factory.setSizeThreshold(config.fileupload().sizeThreshold());
    }
    if (config.fileupload().repository() != null) {
        factory.setRepository(config.fileupload().repository());
    }

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

    // Set overall request size constraint
    if (config.fileupload().sizeMax() != null) {
        upload.setSizeMax(config.fileupload().sizeMax());
    }
    if (config.fileupload().fileSizeMax() != null) {
        upload.setFileSizeMax(config.fileupload().fileSizeMax());
    }
    // Copy params from query string
    Enumeration<String> paramNames = request.getParameterNames();
    while (paramNames.hasMoreElements()) {
        String paramName = paramNames.nextElement();
        String paramValues[] = request.getParameterValues(paramName);
        if (paramValues != null) {
            this.paramMap.put(paramName, Literal.list(paramValues));
        }
    }

    @SuppressWarnings("unchecked")
    List<FileItem> itemList = upload.parseRequest(request);

    for (FileItem item : itemList) {
        String fieldName = item.getFieldName();
        if (item.isFormField()) {
            List<String> values = paramMap.get(fieldName);
            if (values == null) {
                paramMap.put(fieldName, Literal.list(item.getString()));
            } else {
                values.add(item.getString());
            }
        } else {
            fileItemMap.put(fieldName, item);
            fileItems.add(item);
        }
    }
}

From source file:com.br.ifpb.servlet.UploadImagemPerfil.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from w  w  w.ja  v a2s.  c  o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Usuario usuario = ((Usuario) request.getSession().getAttribute("usuario"));
    if (usuario == null) {
        response.sendRedirect("");
    } else {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = null;
            try {
                items = (List<FileItem>) upload.parseRequest(request);
            } catch (FileUploadException ex) {
                Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex);
            }
            FileItem item = items.get(0);
            if (item != null) {
                String nome_arquivo = String.valueOf(new Date().getTime()) + item.getName();
                String caminho = getServletContext().getRealPath("/imagens") + "\\" + usuario.getId() + "\\";
                File file = new File(caminho);
                if (!file.exists()) {
                    file.mkdirs();
                }
                File uploadedFile = new File(caminho + nome_arquivo);
                try {
                    item.write(uploadedFile);
                } catch (Exception ex) {
                    Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex);
                }
                GerenciarUsuario gerenciarUsuario = new GerenciarUsuario();
                try {
                    gerenciarUsuario.atualizarFotoPerfil("imagens" + "/" + usuario.getId() + "/" + nome_arquivo,
                            usuario.getId());
                } catch (PersistenciaException ex) {
                    Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex);
                }
                GerenciarFotos gerenciarFotos = new GerenciarFotos();
                try {
                    gerenciarFotos.publicarFoto("imagens" + "/" + usuario.getId() + "/" + nome_arquivo,
                            Timestamp.valueOf(LocalDateTime.now()), usuario);
                } catch (PersistenciaException ex) {
                    Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex);
                }
                try {
                    usuario = gerenciarUsuario.getUsuario(usuario.getId());
                } catch (PersistenciaException ex) {
                    Logger.getLogger(UploadImagemPerfil.class.getName()).log(Level.SEVERE, null, ex);
                }
                request.getSession().setAttribute("usuario", usuario);
                response.sendRedirect("configuracao");
            } else {

            }
        }

    }
}