How to make a servlet wait to see if it has uploaded the file before redirecting


I wanted to ask you if it occurs to you how to do that after uploading a photograph to a folder on the server, from the same servlet that uploads the image it is verified that the image is fully uploaded before redirecting to another page.

Everything comes because on the next page the image is shown, and it happens to me that sometimes before the image has been uploaded to the server the servlet has redirected to the other page and the image can not be displayed yet .

It has occurred to me with the class file, to check that until it is fully uploaded in this case the two photos do not redirect to another page, and even though it checks them, I can not think of exactly how to validate it. I explain, with an if is going to pass the condition seeing that the image is still not loaded and there is for the servlet without redirecting to the other page, being not expected. And with a while loop it has not worked for me, among others I have put the empty loop, which is not the right thing to do, but it also does not work.

I paste the code a bit in case it helps more to orient what I would ask:


protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    try {

* Aqui estamos confirmando el MultipartFormDataRequest y le indicamos que recoja todo lo que
* nos esta mandando el index.
        MultipartFormDataRequest mrequest = new MultipartFormDataRequest(request);

        String nombre = mrequest.getParameter("nombre");
        String descripcion = mrequest.getParameter("descripcion");

        //mirar video de youtube en carpeta JAVA y comentar codigo

        JDBC helper = new JDBC();

        String consultaSQL = "SELECT RutaCarpetaLocal FROM path where NombreCarpeta='Fotos1'";
        ResultSet   rs = helper.Select(consultaSQL);
        /*en este caso en el servidor hay que poner la ruta especifica hasta la carpeta local en el servidor
                     * la de fotos actuales y la otra carpeta de fotos antiguas
                 al estilo: C:\xampp\tomcat\webapps\BackEnd\Images\Fotos1
                 para que la libreria uploadBean pueda subir hasta esa carpeta.

        String RutaCarpetaLocal1 = "";
        String RutaCarpetaLocal2 = "";

        if ( {
            RutaCarpetaLocal1 = rs.getString("RutaCarpetaLocal");

        String consultaSQL2 = "SELECT RutaCarpetaLocal FROM path where NombreCarpeta='Fotos2'";
        ResultSet  rs2 = helper.Select(consultaSQL2);

        if ( {
            RutaCarpetaLocal2 = rs2.getString("RutaCarpetaLocal");

        UploadBean upBean = null;

             * Usamos un HashTable que es un directorio, se podria usar como una tabla pequeña.
             * mrequest.getFiles() = recoger todos los archivos de la imagen.
        Hashtable files = mrequest.getFiles();
     * si UploadBean sirve para que podamos subir al servidor objetos, entonces 
     * UploadFile sirve para poder subir Archivos al servidor.
     * En este caso, al usar el comando GET, le estamos diciendo a lo que
     * tenga dentro de sus parentecis se vaya al objeto file, pero como 
     * el objeto que obtenemos es de tipo Hashtable le colocamos un cast
     * para que podamos recuperar la informacion si problemas.
        UploadFile file = (UploadFile) files.get("Foto1");

        String name1 = file.getFileName();

        UploadFile file2 = (UploadFile) files.get("Foto2");

        String name2 = file2.getFileName();

        * Empezamos a utilizar el UploadBean y colocamos la opcion setFolderstore
        * para poder indicar en que direcion vamos a guarda todo archivo que nos mande.
        upBean = new UploadBean();


     * Con el Store le decimos al MultipartFormRequest que obtenta tambien la imagen.
     */, "Foto1");

        * Empezamos a utilizar el UploadBean y colocamos la opcion setFolderstore
        * para poder indicar en que direcion vamos a guarda todo archivo que nos mande.
        upBean = new UploadBean();


                 * Con el Store le decimos al MultipartFormRequest que obtenga tambien la imagen.
                 */, "Foto2");

        int IdUsuario = 1;

        String usuario = "admin";
        Connection Conexion;
        Conexion = helper.Conexion();

        PreparedStatement misentencia;
        misentencia = Conexion.prepareStatement("INSERT INTO imagenes VALUES (?,?,?,?,?,?,?)");

        misentencia.setInt(1, 0);
        misentencia.setString(2, nombre);
        misentencia.setString(3, descripcion);

        misentencia.setString(4, name1);
        misentencia.setString(5, name2);
        misentencia.setInt(6, IdUsuario);
        misentencia.setString(7, usuario);



    } catch(Exception ex){


Thanks in advance for the ideas!


asked by Raul Dajani 28.05.2018 в 15:34

1 answer


The documentation is very poor, but it does not seem that the methods for saving files be asynchronous: in principle I would expect that when, "Foto2");

has been completed, the file is already saved. You could do a check with something like

File f= new File(<path>);
while (!f.exists() || f.length() < file2.getFileSize()) {
    // no está grabado
    this.wait(1000); //esperar un segundo

But I would really be surprised if this was the origin of the problem

answered by 29.05.2018 в 18:34