Render .csv file on browser instead of downloading

In my Spring-boot application, to render the files of types .txt, .pdf I am setting the HttpHeader with the following properties.

private HttpHeaders getAppropriateHeaders( String fileType, String fileName )
{
    HttpHeaders headers = new HttpHeaders();

    switch ( fileType )
    {
        case FileConstants.PDF_TYPE :
            headers.setContentType(MediaType.APPLICATION_PDF);
            break;

        case FileConstants.TXT_TYPE :
            headers.setContentType(MediaType.TEXT_PLAIN);
            break;

        case FileConstants.PNG_TYPE :
            headers.setContentType(MediaType.IMAGE_PNG);
            break;

        case FileConstants.JPEG_TYPE :
            headers.setContentType(MediaType.IMAGE_JPEG);
            break;

        default :
            // If set file will be downloaded
            headers.setContentDispositionFormData(fileName, fileName);
            break;
    }

    headers.add("content-disposition", "inline;filename=" + fileName);
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");

    return headers;

}

So far the pdf, txt, png, jpeg files are being rendered on the browser. But What I need to do render .csv files in the same way? What contentType should be set in the HttpResponse?

Answer

The Content-Disposition header you are setting tells the browser that you would like to show contents of the file inline in the browser:

headers.add("content-disposition", "inline;filename=" + fileName);

The browser will do it, if that’s supported. For example, showing PDF files inline in the browser is supported by most, if not all, modern browsers; with CSV, it’s quite the opposite.

However, the error your are getting (described in the comment: localhost sent an invalid response. ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION), is correct for CSV files, because you are setting Content-Disposition header twice for CSV: first time in the default case for switch statement, second time after the switch statement).

Correct it by handling text/csv in your switch statement.

Leave a Reply

Your email address will not be published. Required fields are marked *