0

Excelente comunidad! :) Les traigo una consulta. Estoy tratando de hacer un formulario con Java que recibe un texto, una fecha y un archivo. El archivo es subido al servidor, obtiene el link del archivo, y lo almacena en una base de datos.

Primero habia hecho la parte en que sube la fecha y texto a la base de datos, ahora estoy intentando agregarle la parte en que se sube el archivo al servidor, y por alguna razon estoy fallando al hacerlo.

Aqui mi codigo:

Formulario:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%
    String usuario = "";
    HttpSession sesionOk = request.getSession();
    if (sesionOk.getAttribute("usuario") == null) { //Verifica que este logueado
    %>
        <jsp:forward page="login.jsp"/>
    <%
    } else {
        usuario = (String)sesionOk.getAttribute("usuario");
    }
%>

<html>
    <head>
        <meta charset="UTF-8">

        <link href="https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300,700" rel="stylesheet">

        <link rel="stylesheet" type="text/css" href="editar.css">
        <title>Legislatura Pro Cordoba Sur</title>
    </head>

    <body>

            <header> MENU -> <%=usuario%> - <a href="cerrarsesion.jsp">Cerrar Sesion</a> </header>

        <div id="mainContainer">

                    <FORM id="formulario" action="agregarComentarioServlet?codigo=<%= request.getParameter("codigo") %>" method="POST">
                            <table id="tablaForm">
                            <tr>
                                <td class="labelD">Fecha:</td> <td><input type="date" size=30 value="" name="fecha"/></td>
                            </tr>
                            <tr>
                                <td class="label">Texto:</td><td colspan="3"><input type="text" size=80 value="" name="texto"/></td>
                            </tr>
                            <tr>
                                <td class="label">Agregar adjunto</td><td><input type="file" size=30 value="" name="filename"/></td>
                            </tr>
                            <tr>
                                <td colspan="4" class="Cabecera"><input class="boton" type="submit" name="agregar" value="Agregar"/></td>
                            </tr>

                            </table>

            </FORM>
                    <br>
                    <br>
                    <br> ${requestScope.error}

        </div>

        <footer>Pro Cordoba Sur  - 2016</footer>

    </body>
</html>

Servlet:

import com.mysql.jdbc.Connection;
import java.io.File;
import java.io.IOException;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

/**
 *
 * @author Facu
 */
@WebServlet(urlPatterns = {"/agregarComentarioServlet"})
@MultipartConfig(fileSizeThreshold=1024*1024*10,    // 10 MB 
                 maxFileSize=1024*1024*50,          // 50 MB
                 maxRequestSize=1024*1024*100)      // 100 MB
public class agregarComentarioServlet extends HttpServlet {
    private static final String UPLOAD_DIR = "archivos";
    Connection connection;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession sesionOk = request.getSession();

        if ( (sesionOk.getAttribute("usuario") == null) ){//Verifica que este logueado
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }

        if(request.getParameter("codigo")==null){
            String error="<div class=error>Intentando agregar un comentario sin codigo</div>";
            request.setAttribute("error", error);
            request.getRequestDispatcher("menuServlet").forward(request, response);
        }

        try {
            connectDB();
        } catch (SQLException ex) {
            String error="<div class=error>Error al conectar con la base de datos</div>";
            request.setAttribute("error", error);
            request.getRequestDispatcher("menu.jsp").forward(request, response);

        } catch (ClassNotFoundException ex) {
            String error="<div class=error>Driver no cargado</div>";
            request.setAttribute("error", error);
            request.getRequestDispatcher("menu.jsp").forward(request, response);
        }

        subirArchivo(request, response);

        PreparedStatement preparedStmt=null;
        try {

            String sql="INSERT INTO comentario (fecha, codigo, texto) VALUES (?,?,?)";

            String fecha= request.getParameter("fecha");
            String codigoStr=request.getParameter("codigo");
            int codigo=Integer.parseUnsignedInt(codigoStr);
            String texto=request.getParameter("texto");

            preparedStmt = connection.prepareStatement(sql);
            preparedStmt.setString(1, fecha);
            preparedStmt.setInt(2, codigo);
            preparedStmt.setString(3, texto);

            preparedStmt.execute();
            request.getRequestDispatcher("editarServlet?codigo="+codigo).forward(request, response);


        } catch (SQLException ex) {
            String error="<div class=error>La consulta es incorrecta</div>";
            request.setAttribute("error", error);
            request.getRequestDispatcher("menu.jsp").forward(request, response);
        }catch (NumberFormatException ex){
            String error="<div class=error>El estado es invalido</div>";
            request.setAttribute("error", error);
            request.getRequestDispatcher("menuServlet").forward(request, response);
        }finally{
                try { if (preparedStmt != null) preparedStmt.close(); } catch (Exception e) {};
                try { if (connection != null) connection.close(); } catch (Exception e) {};
        }
    }

    void connectDB() throws SQLException, ClassNotFoundException{

        Class.forName("com.mysql.jdbc.Driver"); //Carga el driver

        String url = "jdbc:mysql://127.0.0.1:3306/expediente";
        String username = "root";
        String password = "123456";

        connection = (Connection) DriverManager.getConnection(url, username, password);

    }

    String subirArchivo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        try {
            // gets absolute path of the web application
            String applicationPath = request.getServletContext().getRealPath("");
            // constructs path of the directory to save uploaded file
            String uploadFilePath = applicationPath + File.separator + UPLOAD_DIR;
            // creates the save directory if it does not exists
            File fileSaveDir = new File(uploadFilePath);
            if (!fileSaveDir.exists()) {
                fileSaveDir.mkdirs();
            }
            String fileName = null;
            //Get all the parts from request and write it to the file on server
            for (Part part : request.getParts()) {
                fileName = (String) getFileName(part);
                part.write(uploadFilePath + File.separator + fileName);
            }
            return fileName;

        } catch (IOException | ServletException ex) {
            String error="<div class=error>Error al subir el archivo</div>";
            request.setAttribute("error", error);
            request.getRequestDispatcher("menu.jsp").forward(request, response);
        }

        return "";
    }

    private String getFileName(Part part) {
        String contentDisp = part.getHeader("content-disposition");
        String[] tokens = contentDisp.split(";");
        for (String token : tokens) {
            if (token.trim().startsWith("filename")) {
                return token.substring(token.indexOf("=") + 2, token.length()-1);
            }
        }
        return "";
    }


    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @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
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @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
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

}

Y aqui el error que me larga:

java.lang.IllegalStateException: No puedo reenviar después de que la respuesta se haya llevado a cabo.
    agregarComentarioServlet.processRequest(agregarComentarioServlet.java:73)
    agregarComentarioServlet.doPost(agregarComentarioServlet.java:168)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

Aclaro que la parte de subir el archivo al server no es mio, la verdad que no tenia ni idea como hacerlo, asique me guíe con este tutorial: http://www.journaldev.com/2122/servlet-3-file-upload-multipartconfig-part

De todas formas no explica bien como funciona, y no entendí mucho lo que hice (ahi la razón de que falle :/) Asique si alguien me puede explicar y ayudar a corregir el error, se lo agradeceria muchooo.


Actualizacion:

Siguiendo esta ayuda: https://stackoverflow.com/questions/2422468/how-to-upload-files-to-server-using-jsp-servlet

He logrado subir el archivo al servidor. Aquí el codigo:

String subirArchivo(int codigo, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
    Part filePart = request.getPart("archivo"); // Obtiene el archivo
    String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.

    //InputStream fileContent = filePart.getInputStream(); //Lo transforma en InputStream

    String path="/archivos/";
    File uploads = new File(path); //Carpeta donde se guardan los archivos
    uploads.mkdirs(); //Crea los directorios necesarios
    File file = File.createTempFile("cod"+codigo+"-", "-"+fileName, uploads); //Evita que hayan dos archivos con el mismo nombre

    try (InputStream input = filePart.getInputStream()){
        Files.copy(input, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
    }

    return file.getPath();
}

Sin embargo, estoy teniendo problemas respecto a la ubicacion donde se guarda el archivo... Si en el String path, coloco "/archivos/", el archivo es subido a C://archivos Por lo tanto me es imposible descargarlo, puesto que tomcat no accede a dicho directorio (no me explico como es que hace para subirlo ahi...) Intento descargar: http://localhost:8080/archivos/comentario.csv Y me dice que el recurso no esta disponible.

Si por el contrario, en path coloco el directorio relativo: "./archivos/" El archivo es subido al directorio bin dentro de mi carpeta tomcat. Y tampoco puedo acceder para descargarlo. Como deberia hacer para subirlo a una carpeta a la que tenga acceso?

2
  • 1
    en el form te hace falta la etiqueta enctype="multipart/form-data" ya que es importante para subir archivos
    – J. Castro
    el 17 oct. 2016 a las 17:58
  • Lo he agregado pero sigo teniendo el mismo error :/ el 17 oct. 2016 a las 18:13

2 respuestas 2

2

He encontrado la solucion en: https://stackoverflow.com/questions/2422468/how-to-upload-files-to-server-using-jsp-servlet

Me ha quedado el siguiente codigo:

String subirArchivo(int codigo, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
    Part filePart = request.getPart("archivo"); // Obtiene el archivo
    String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.

    //InputStream fileContent = filePart.getInputStream(); //Lo transforma en InputStream

    String path="/archivos/";
    File uploads = new File(path); //Carpeta donde se guardan los archivos
    uploads.mkdirs(); //Crea los directorios necesarios
    File file = File.createTempFile("cod"+codigo+"-", "-"+fileName, uploads); //Evita que hayan dos archivos con el mismo nombre

    try (InputStream input = filePart.getInputStream()){
        Files.copy(input, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
    }

    return file.getPath();
}

El archivo es subido a C:\archivos. Por lo que es necesario agregar:

<Context docBase="C:\archivos" path="/archivos" />

al archivo server.xml de la configuracion de tomcat, dentro de la etiqueta <host>

0

Define una ruta completa de dirección donde guardar el/los archivos

Ej:

directorio=C:/temp/informes 

Importante que este directorio lo tengas creado en el sevidor

Luego en el Java haz:

File miArchivo = new File(directorio, nombreArchivo);

Luego con tu archivo convertido a byte[] puedes hacer:

FileOutputStream zos = null;
        try {
            zos = new FileOutputStream(miArchivo);
        ByteArrayInputStream bais = null;
        try {
            bais = new ByteArrayInputStream(miArchivoByteArray);
            byte[] buffer = new byte[2048];
            int leido = 0;
            while (0 < (leido = bais.read(buffer))) {
                zos.write(buffer, 0, leido);
            }

        } catch (IOException ex) {
            //salida de error
        } finally {
            bais.close();
            zos.close();
        }

Y entonces guarda en la base de datos el path y el nombre

ej:

miArchivo.getAbsolutePath();//ej C:\temp\informes\nombreArchivo
miArchivo.getName();//nombreArchivo

Ahí tienes los nombres de cada caso, los puedes subir y tratar con Java, la BBDD o lo que toque ;) (antes o después del try, eso a tu gusto y según prefieras)

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.