Force the download of a csv file from a servlet

0

I'm doing a java application where you have to download a CSV file. But it is happening to me that the browser does not show the download dialog, but shows it embedded in the browser itself.

This is the code of my servlet:

        List<MisDatosBean> listaDatos = miDAL.obtenerDatos();
        if (listaDatos!= null) {
            PrintWriter writer;
            writer = response.getWriter();
            for (MisDatosBean d : listaDatos) {
                CSVUtils.writeLine(writer, generarLista(d));
            }
            response.setContentType("text/csv");
            response.setHeader("Content-Disposition", "attachment; filename=\"datos.csv\"");
            if (!request.isSecure()) {
                response.setHeader("Cache-Control", "no-cache");
                response.setHeader("Pragma", "no-cache");
                response.setHeader("Expires", "0");
            }
            writer.flush();
            writer.close();
        }

What else should I indicate, so that it shows me the download dialog? It happens to me in all the browsers I've tried, both IE11, firefox and chrome.

    
asked by Dani 03.02.2017 в 13:40
source

1 answer

1

Finally, through this answer I have been able to fix it.

The fact is that the description of the header must be done before writing the contents of the file in the output stream.

That is, it would look like this:

        List<MisDatosBean> listaDatos = miDAL.obtenerDatos();
    if (listaDatos!= null) {
        response.setContentType("text/csv");
        response.setHeader("Content-Disposition", "attachment; filename=\"datos.csv\"");
        if (!request.isSecure()) {
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Expires", "0");
        }
        PrintWriter writer;
        writer = response.getWriter();
        for (MisDatosBean d : listaDatos) {
            CSVUtils.writeLine(writer, generarLista(d));
        }
        writer.flush();
        writer.close();
    }

By doing so, the browser already gives the option to download it instead of displaying it.

    
answered by 06.02.2017 / 12:57
source