Example usage for javax.servlet.http Part getSubmittedFileName

List of usage examples for javax.servlet.http Part getSubmittedFileName

Introduction

In this page you can find the example usage for javax.servlet.http Part getSubmittedFileName.

Prototype

public String getSubmittedFileName();

Source Link

Document

Gets the file name specified by the client

Usage

From source file:org.cirdles.webServices.ambapo.AmbapoServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from   w w w  . j av 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 {
    response.setContentType("text/csv");
    response.setHeader("Content-Disposition", "attachment; filename=converted-file.csv");

    String conversionType = ServletRequestUtils.getStringParameter(request, "conversionType", "LatLongtoUTM");
    Part filePart = request.getPart("ambapoFile");

    String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
    InputStream fileStream = filePart.getInputStream();
    File myFile = new File(fileName);

    AmbapoFileHandlerService handler = new AmbapoFileHandlerService();
    String fileExt = FilenameUtils.getExtension(fileName);

    try {
        File convertedFile = null;
        if (fileExt.equals("csv")) {
            convertedFile = handler.convertFile(fileName, fileStream, conversionType).toFile();
            response.setContentLengthLong(convertedFile.length());
            IOUtils.copy(new FileInputStream(convertedFile), response.getOutputStream());
        }

        else {
        }

    } catch (Exception e) {
        System.err.println(e);
    }

}

From source file:org.cirdles.webServices.calamari.CalamariServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*w  ww  . ja  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 {

    HttpSession session = request.getSession();
    Integer accessCount;
    synchronized (session) {
        accessCount = (Integer) session.getAttribute("accessCount");
        if (accessCount == null) {
            accessCount = 0; // autobox int to Integer
        } else {
            accessCount = accessCount + 1;
        }
        session.setAttribute("accessCount", accessCount);
    }

    response.setContentType("application/zip");
    response.setHeader("Content-Disposition", "attachment; filename=calamari-reports.zip");

    boolean useSBM = ServletRequestUtils.getBooleanParameter(request, "useSBM", true);
    boolean useLinFits = ServletRequestUtils.getBooleanParameter(request, "userLinFits", false);
    String firstLetterRM = ServletRequestUtils.getStringParameter(request, "firstLetterRM", "T");
    Part filePart = request.getPart("prawnFile");

    String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
    InputStream fileStream = filePart.getInputStream();
    File myFile = new File(fileName);

    PrawnFileHandlerService handler = new PrawnFileHandlerService();
    String fileExt = FilenameUtils.getExtension(fileName);

    try {
        File report = null;
        if (fileExt.equals("zip")) {
            report = handler.generateReportsZip(fileName, fileStream, useSBM, useLinFits, firstLetterRM)
                    .toFile();
        } else if (fileExt.equals("xml")) {
            report = handler.generateReports(fileName, fileStream, useSBM, useLinFits, firstLetterRM).toFile();
        }

        response.setContentLengthLong(report.length());
        IOUtils.copy(new FileInputStream(report), response.getOutputStream());

    } catch (Exception e) {
        System.err.println(e);
    }

}

From source file:org.eclipse.equinox.http.servlet.tests.ServletTest.java

public void test_Servlet16() throws Exception {
    Servlet servlet = new HttpServlet() {
        private static final long serialVersionUID = 1L;

        @Override/* w w  w .j  a v a2 s  .c o m*/
        protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws IOException, ServletException {

            Part part = req.getPart("file");
            Assert.assertNotNull(part);

            String submittedFileName = part.getSubmittedFileName();
            String contentType = part.getContentType();
            long size = part.getSize();

            PrintWriter writer = resp.getWriter();

            writer.write(submittedFileName);
            writer.write("|");
            writer.write(contentType);
            writer.write("|" + size);
        }
    };

    Dictionary<String, Object> props = new Hashtable<String, Object>();
    props.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_NAME, "S16");
    props.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_PATTERN, "/Servlet16/*");
    props.put("equinox.http.multipartSupported", Boolean.TRUE);
    registrations.add(getBundleContext().registerService(Servlet.class, servlet, props));

    Map<String, List<Object>> map = new HashMap<String, List<Object>>();

    map.put("file", Arrays.<Object>asList(getClass().getResource("resource1.txt")));

    Map<String, List<String>> result = requestAdvisor.upload("Servlet16/do", map);

    Assert.assertEquals("200", result.get("responseCode").get(0));
    Assert.assertEquals("resource1.txt|text/plain|1", result.get("responseBody").get(0));
}

From source file:org.mhi.servlets.ImageUpload.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    request.setCharacterEncoding("UTF-8");

    // Service Class for DB - Actions
    ServiceQuery query = new ServiceQuery();
    ServiceUpdate update = new ServiceUpdate();

    String imgName = request.getParameter("name");
    String imgDesc = request.getParameter("desc");
    String imgCat = request.getParameter("category");
    String fileSize = null;/*from  ww w  .j av  a 2 s.c  o  m*/
    String fileName = null;
    String contentType = null;
    String[] parts = null;

    InputStream inputStream = null; // input stream of the upload file

    // obtains the upload file part in this multipart request
    Part filePart = request.getPart("files");

    if (filePart != null) {
        // Fill up Information extract from File
        fileSize = "" + filePart.getSize();
        parts = filePart.getSubmittedFileName().split("\\.");
        contentType = filePart.getContentType();

        // obtains input stream of the upload file
        inputStream = filePart.getInputStream();

        // new Image
        Images img = new Images();
        // Set Parameters
        img.setFileName(imgName + "." + parts[1]);
        img.setName(imgName);
        img.setDescription(imgDesc);
        img.setFileBlob(IOUtils.toByteArray(inputStream));
        img.setFileSize(fileSize);
        img.setcTyp(contentType);
        // Relationship to Category
        ImgCat cat = query.getCategoryByID(Long.valueOf(imgCat));
        img.setCategory(cat);
        // Persist to Database
        update.insertImage(img);
    }
    response.sendRedirect(request.getServletContext().getContextPath() + "/admin/upload");

}

From source file:org.sonar.server.ws.ServletRequest.java

@Override
@CheckForNull//from  ww w  .ja  v a2  s.  c o  m
public Part readPart(String key) {
    try {
        if (!isMultipartContent()) {
            return null;
        }
        javax.servlet.http.Part part = source.getPart(key);
        if (part == null || part.getSize() == 0) {
            return null;
        }
        return new PartImpl(part.getInputStream(), part.getSubmittedFileName());
    } catch (Exception e) {
        throw new IllegalStateException("Can't read file part", e);
    }
}

From source file:pe.edu.upeu.application.web.controller.CVacaciones.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//w  w  w  . j  a  v a  2 s . 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 {
    PrintWriter out = response.getWriter();
    Map<String, Object> mp = new HashMap<String, Object>();
    InterfaceDgpDAO dgp = new DgpDAO();
    ContratoDAO cD = new ContratoDAO();
    VacacionDAO vC = new VacacionDAO();

    InterfaceVacacionesDAO vaca = new VacacionDAO();
    DocumentoDAO d = new DocumentoDAO();
    Detalle_VacacionDAO Dvac = new Detalle_VacacionDAO();
    HttpSession sesion = request.getSession(true);
    String iddir = (String) sesion.getAttribute("IDDIR");
    String iddep = (String) sesion.getAttribute("DEPARTAMENTO_ID");
    String user = (String) sesion.getAttribute("IDUSER");
    String contentType = request.getContentType();
    System.out.println("contentType = " + contentType);

    boolean isMultipart = ServletFileUpload.isMultipartContent(request); // Check that we have a file upload request
    System.out.println("isMultipart = " + isMultipart);
    if (isMultipart) {

        String opc = request.getParameter("opc");// Retrieves all text inputs
        if (opc.equals("asign")) {
            Part filePart = request.getPart("docadj"); // Retrieves <input type="file" name="file">
            response.setContentType("application/json;charset=UTF-8");
            String idcon = (String) sesion.getAttribute("id_con_vac");
            System.out.println(opc);
            String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.
            System.out.println(fileName);

            String renombre_archivo = null;
            Calendar fecha = new GregorianCalendar();
            int hora = fecha.get(Calendar.HOUR_OF_DAY);
            int min = fecha.get(Calendar.MINUTE);
            int sec = fecha.get(Calendar.SECOND);
            renombre_archivo = String.valueOf(hora) + String.valueOf(min) + String.valueOf(sec) + "_" + idcon
                    + "_" + fileName.toUpperCase();
            System.out.println(renombre_archivo);

            //           String ubicacionArchivo = "";
            //           ubicacionArchivo = FactoryConnectionDB.url + "Archivo/";
            //                // ubicacion = getServletContext().getRealPath(".").substring(0, getServletContext().getRealPath(".").length() - 11) + "web\\Vista\\Usuario\\Fotos";
            //                DiskFileItemFactory f = new DiskFileItemFactory();
            //                f.setSizeThreshold(1024);
            //                f.setRepository(new File(ubicacionArchivo));
            //                ServletFileUpload upload = new ServletFileUpload(f);
            String Descripcion = request.getParameter("dest");
            String Estado = request.getParameter("est");
            System.out.println(Descripcion);
            System.out.println(Estado);
            String iddaj = d.INSERT_DOCUMENTO_ADJUNTO(null, iddep, "1", user, null, null, null, null,
                    Descripcion, null, Estado, idcon).trim();

            System.out.println(iddaj);
            d.INSERT_ARCHIVO_DOCUMENTO(null, iddaj, renombre_archivo, fileName, null);
            String idvac = vC.insert_vacation(iddaj, idcon);
            //  System.out.println("idvac: "+idvac);
            //  System.out.println("iddaj: "+iddaj);
            //  System.out.println("idcon: "+idcon);
            if (idcon != null) {
                System.out.println("aaaa:" + idvac);
                mp.put("info", idvac);
            } else {
                mp.put("info", "-1");
            }
            Gson gson = new Gson();
            out.println(gson.toJson(mp));
            out.flush();
            out.close();
        }

    } else {
        String opc = request.getParameter("opc");
        if (opc.equals("rolrequest")) {
            response.setContentType("application/json;charset=UTF-8");
            String idrol = (String) sesion.getAttribute("IDROL");
            System.out.println(idrol);
            mp.put("idrol", idrol);
            Gson gson = new Gson();
            out.println(gson.toJson(mp));
            out.flush();
            out.close();
        }
        if (opc.equals("Listar")) {
            response.sendRedirect("Vista/Vacaciones/Lista_Empleados.jsp");
        }
        if (opc.equals("listartadm")) {
            response.sendRedirect("Vista/Vacaciones/List_Trab_Adm.jsp");
        }
        if (opc.equals("listaraut")) {
            response.sendRedirect("Vista/Vacaciones/List_Trab_Adm.jsp");
        }
        if (opc.equals("listTA")) {
            response.setContentType("application/json;charset=UTF-8");
            System.out.println("llega");
            mp.put("aptos", vC.trabajadoresapt());
            Gson gson = new Gson();
            out.println(gson.toJson(mp));
            out.flush();
            out.close();
        }
        if (opc.equals("listadm")) {
            response.setContentType("application/json;charset=UTF-8");
            String idep = (String) sesion.getAttribute("DEPARTAMENTO_ID");
            mp.put("adm", vC.trabajadoresadm(idep));
            Gson gson = new Gson();

            out.println(gson.toJson(mp));
            out.flush();

            out.close();
        }
        if (opc.equals("listToAut")) {
            response.setContentType("application/json;charset=UTF-8");
            String idep = (String) sesion.getAttribute("DEPARTAMENTO_ID");
            mp.put("adm", vC.ListToAut(idep));
            Gson gson = new Gson();

            out.println(gson.toJson(mp));
            out.flush();

            out.close();
        }
        if (opc.equals("AutorizAN")) {
            response.setContentType("application/json;charset=UTF-8");
            String[] id_au = request.getParameterValues("AutorizAN");
            List<String> list = new ArrayList<String>();
            for (int i = 0; i < id_au.length; i++) {
                list.add(id_au[i]);
            }
            boolean a = vC.admitirV(list);
            if (a) {
                response.sendRedirect("Vista/Vacaciones/Lista_Empleados.jsp");
                //ok
            } else {
                //error
            }
            //System.out.println(a);
            /*sesion.setAttribute("lista", list);
             response.sendRedirect("Vista/Contrato/Formato_Plantilla/Impresion_Masiva.jsp");*/
        }
        if (opc.equals("sendcon")) {
            String idcon = request.getParameter("idcon");
            System.out.println(idcon);
            sesion.setAttribute("id_con_vac", idcon);
            response.sendRedirect("Vista/Vacaciones/prog_vacaciones.jsp");
        }
        if (opc.equals("get_info_trab")) {
            response.setContentType("application/json;charset=UTF-8");
            System.out.println("hola que hace");
            System.out.println("ola k ase");
            String idcon = (String) sesion.getAttribute("id_con_vac");
            System.out.println(idcon);
            if (idcon != null) {
                mp.put("info", vC.get_info_trab(idcon));
            } else {
                mp.put("info", "-1");
            }
            Gson gson = new Gson();

            out.println(gson.toJson(mp));
            out.flush();

            out.close();
        }

        if (opc.equals("Procesar")) {
            String iddgp = "";
            String idpro = "";
            try {
                iddgp = CCriptografiar.Desencriptar(request.getParameter("dgp"));
                idpro = CCriptografiar.Desencriptar(request.getParameter("proceso"));
            } catch (Exception ex) {
                System.out.println("Error: " + ex);
            }
            if (iddgp.equals("") && idpro.equals("")) {
                vaca.PROCESAR_VACACIONES(idpro, iddgp);
            }
            response.sendRedirect("Vista/Vacaciones/Proceso_Vacacion.jsp");
            mp.put("rpta", true);

        }
        if (opc.equals("listEsVacaciones")) {
            mp.put("list", dgp.LIST_DGP_PROCESO(iddep, "", true));
        }

        //             if (opc.equals("asign")) {
        //                 response.setContentType("application/json;charset=UTF-8");
        //                 String idcon = (String) sesion.getAttribute("id_con_vac");
        //                 String idvac = "DOC-0002";
        //                 if (idcon != null) {
        //                   mp.put("info", idvac);
        //                } else {
        //                    mp.put("info", "-1");
        //                }
        //                Gson gson = new Gson();
        // 
        //                 out.println(gson.toJson(mp));
        //                 out.flush();
        // 
        //                 out.close();
        //              }
        if (opc.equals("asigndv")) {

            String idDetvac = null;
            String fedesde = request.getParameter("from");
            String fehasta = request.getParameter("to");
            //String idvacacion = "1";
            String idvacacion = request.getParameter("idvac");
            // System.out.println(idvacacion);
            System.out.println(fedesde + " " + fehasta + " " + idvacacion);
            Detalle_VacacionDAO MoDet_Vac = new Detalle_VacacionDAO();
            Detalle_Vacacion Detv = new Detalle_Vacacion();

            Detv.setIddetalle(null);
            Detv.setFe_inicio(fedesde);
            Detv.setFe_fin(fehasta);
            Detv.setIdvacacion(idvacacion);

            //
            //                Dvac.insert(MoDet_Vac);

            MoDet_Vac.insert(Detv);
            // sesion.setAttribute("List_Usuario_var", usu.List_Usuario_var());

            response.setContentType("application/json;charset=UTF-8");

            Gson gson = new Gson();
            out.println(gson.toJson(mp));
            out.flush();
            out.close();
        }
    }

    try {

    } finally {
        out.close();
    }
}

From source file:servlets.post.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//ww  w .j  a  va2 s  .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");
    PrintWriter out = response.getWriter();
    JsonObject resp = new JsonObject();
    try {
        String tipo = request.getParameter("tipo") == null ? "" : request.getParameter("tipo");
        String titulo = request.getParameter("titulo") == null ? "" : request.getParameter("titulo");
        String descripcion = request.getParameter("descripcion") == null ? ""
                : request.getParameter("descripcion");
        int categoria = request.getParameter("categoria") == null ? -1
                : Integer.parseInt(request.getParameter("categoria"));

        //Si los campos estan vacios: error de validacion
        if (tipo.equals("") || titulo.equals("") || descripcion.equals("") || categoria == -1) {
            throw new Exception("W::No puedes dejar campos vacios. Intentalo nuevamente");
        }

        Part imagen = request.getPart("contenido");
        Part audio = request.getPart("audio");
        String cabeceraI = "";
        String cabeceraA = "";

        boolean siimagen = false;
        if (imagen != null && !imagen.getContentType().equals("application/octet-stream")) {
            cabeceraI = request.getParameter("cabeceraI") == null ? "" : request.getParameter("cabeceraI");
            if (cabeceraI.equals(""))
                throw new Exception("W::tu imagen no tiene cabecera. Agregale una antes de enviar los datos");
            else
                siimagen = true;
        }
        boolean siaudio = false;
        if (audio != null && !audio.getContentType().equals("application/octet-stream")) {
            cabeceraA = request.getParameter("cabeceraA") == null ? "" : request.getParameter("cabeceraA");
            if (cabeceraA.equals(""))
                throw new Exception("W::tu archivo no tiene cabecera. Agregale uno antes de enviar los datos");
            else
                siaudio = true;
        }

        HttpSession ss = request.getSession();
        int db = ss.getAttribute("bd") == null ? -1 : Integer.parseInt(ss.getAttribute("bd").toString());
        int id = ss.getAttribute("id") == null ? -1 : Integer.parseInt(ss.getAttribute("id").toString());
        if (db == -1 || id == -1)
            throw new Exception("Problemas con la base de datos. Por favor, intentalo mas tarde");

        ldn.cPost post = new ldn.cPost(db);
        String msg = post.nuevoPost(id, categoria, titulo, descripcion);
        if (post.getIdP() == -1)
            throw new Exception(msg);
        //msg se manda como error si idP = -1

        String result = "";
        if (siimagen) {
            String extension = FilenameUtils.getExtension(imagen.getSubmittedFileName());
            result = Clases.Utilities.saveFile(imagen, "imagenPost", "imagen", "." + extension);
            if (result.startsWith("/"))
                result = post.registraContenidoP(Integer.toString(post.getIdP()), result, cabeceraI);
            else
                throw new Exception(result);
            msg += "\n" + result;
        }
        if (siaudio) {
            String extension = FilenameUtils.getExtension(audio.getSubmittedFileName());
            System.out.println(extension);
            result = Clases.Utilities.saveFile(audio, "audioPost", "audio", "." + extension);
            if (result.startsWith("/"))
                result = post.registraContenidoP(Integer.toString(post.getIdP()), result, cabeceraA);
            else
                throw new Exception(result);
            msg += "\n" + result;
        }
        resp.addProperty("status", "OK");
        resp.addProperty("msg", msg);
    } catch (Exception e) {
        if (e.getMessage().startsWith("W::")) {
            resp.addProperty("status", "WARNING");
            resp.addProperty("msg", e.getMessage().substring(3));
        } else {
            resp.addProperty("status", "ERROR");
            resp.addProperty("msg", e.getMessage());
        }
    }
    out.print(resp.toString());
}

From source file:uk.ac.dundee.computing.aec.instagrim.servlets.EditProfile.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//ww  w  .  j a va 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
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Part part = request.getPart("upfile");
    System.out.println("Part Name " + part.getName());
    String type = part.getContentType();
    String filename = part.getSubmittedFileName();
    InputStream is = request.getPart(part.getName()).getInputStream();
    int i = is.available();
    HttpSession session = request.getSession();
    LoggedIn lg = (LoggedIn) session.getAttribute("LoggedIn");
    String username = "majed";
    if (lg.getlogedin()) {
        username = lg.getUsername();
    }
    if (i > 0) {
        byte[] b = new byte[i + 1];
        is.read(b);
        System.out.println("Length : " + b.length);
        PicModel tm = new PicModel();
        tm.setCluster(cluster);
        String message = " ";
        java.util.UUID picid = tm.insertPic(b, type, filename, username, message);
        session.setAttribute("picid", picid);
        is.close();
    }

    PrintWriter out = response.getWriter();
    User u = new User();
    u.setCluster(cluster);
    String first_name = (String) request.getParameter("first_name");
    String last_name = (String) request.getParameter("last_name");
    String interest = (String) request.getParameter("interest");
    String email = (String) request.getParameter("email");
    String address = (String) request.getParameter("address");
    out.println(first_name);
    java.util.UUID picid;
    picid = (java.util.UUID) session.getAttribute("picid");
    u.setUserProfile(username, first_name, last_name, interest, email, address, picid);
    java.util.LinkedList<String> userProfile = u.getUserProfile(username);
    session.setAttribute("profile", userProfile);
    RequestDispatcher rd = request.getRequestDispatcher("profile.jsp");
    rd.forward(request, response);
}

From source file:vista.RegistroVideojuegoServlet.java

private byte[] convierteArchivo(Part filePart, int tipo) {
    InputStream fileContent = null;
    byte[] imagen = null;
    try {//from  www  .j  a  va 2s .c  om
        InputStream inputStream = filePart.getInputStream();
        String fileName = filePart.getSubmittedFileName();
        String ext = fileName.substring(fileName.indexOf("."));
        boolean validacion = tipo == 1 ? validaNombreVideo(ext)
                : tipo == 0 ? validaNombreImagen(ext) : validaNombreArchivo(ext);
        fileContent = filePart.getInputStream();
        //String nombreArchivo = validaHistorial(fileName, fileContent, usuario, email);
        if (validacion) {
            imagen = new byte[inputStream.available()];
            imagen = IOUtils.toByteArray(inputStream);
        }

    } catch (IOException ex) {
        Logger.getLogger(RegistroVideojuegoServlet.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            fileContent.close();
            return imagen;
        } catch (IOException ex) {
            Logger.getLogger(RegistroVideojuegoServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return imagen;
}