Upload file to Java server ee

0

Excellent community! :) I bring you a query. I am trying to make a form with Java that receives a text, a date and a file. The file is uploaded to the server, gets the link from the file, and stores it in a database.

First I had done the part in which the date and text is uploaded to the database, now I am trying to add the part where the file is uploaded to the server, and for some reason I am failing to do so.

Here my code:

Form:

<%@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);
    }

}

And here's the error that takes me:

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)

I clarify that the part of uploading the file to the server is not mine, the truth is that I had no idea how to do it, so guide me with this tutorial: link

Anyway, it does not explain well how it works, and I did not understand much what I did (there the reason why it fails: /) So if someone can explain and help me correct the error, I would appreciate it a lot.

Update:

Following this help: link

I have managed to upload the file to the server. Here the code:

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();
}

However, I am having problems regarding the location where the file is saved ... If in the String path, I place "/ files /", the file is uploaded to C: // files Therefore it is impossible for me to download it, since tomcat does not access this directory (I do not understand how it is to upload it there ...) I try to download: link And he tells me that the resource is not available.

If instead, in path I put the relative directory: "./files/" The file is uploaded to the bin directory inside my tomcat folder. And I can not access to download it either. What should I do to upload it to a folder that I have access to?

    
asked by Facundo Curti 17.10.2016 в 19:48
source

2 answers

2

I found the solution in: link

I have the following code:

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();
}

The file is uploaded to C: \ files. So it is necessary to add:

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

to the server.xml file of the tomcat configuration, inside the <host> tag

    
answered by 18.10.2016 / 00:37
source
0

Defines a complete address path to save the file

Ex:

directorio=C:/temp/informes 

Important that this directory is created on the server

Then in Java, do:

File miArchivo = new File(directorio, nombreArchivo);

Then with your file converted to byte [] you can do:

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();
        }

And then save the path and name in the database

ex:

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

There you have the names of each case, you can upload them and deal with Java, the BBDD or whatever you touch;) (before or after the try, that to your liking and according to your preference)

    
answered by 20.10.2016 в 18:05