Question

I have the following code on Spring Controller

@RequestMapping(value = "/download", method = RequestMethod.POST)
 public void downloadActive(@RequestParam(value = "type") String offerType, HttpServletResponse response,
            HttpSession session) throws Exception {

 StringBuilder b = new StringBuilder();.
.
.

response.addHeader("Content-Disposition: ", "attachment; filename=my" + offerType + "Offers.csv");
response.getWriter().write(b.toString());
..

}

This code get executed when a download button from EXt Js is clicked. On chrome, it directly downloads the file as a *.csv format and when the user opens it, it will use Excel automatically to open the file, if they already have installed and this is the right behavior I wanted to have.

However, on firefox, it prompts a save as window with open with and save options. If I use open with option, it tells me the filename is filename.csv but the type is chrome htm file. I haven't mentioned htm anywhere in my code and I dont know why its trying to open it as htm instead of csv file. Once it tries to open it, it brings excel application and the contents are in a bad format.

Is there a way to avoid this problem on firefox ?

Thanks

Was it helpful?

Solution

Adding double quotes (") for the file name fixes the problem.

response.setHeader("Content-disposition", "attachment; filename=\"" + fileName + "");

OTHER TIPS

Even if I am not sure why it worked, changing the addHeader Method to setHeader fixed the issue.

response.setHeader("Content-Disposition: ", "attachment; filename=my" + offerType + "Offers.csv");
PrintWriter printWriter = resourceResponse.getWriter();
java.util.Date date = new java.util.Date();
resourceResponse.setContentType("text/csv");
resourceResponse.addProperty(HttpHeaders.CACHE_CONTROL,
        "max-age=0, must-revalidate");
resourceResponse.setProperty(
        HttpHeaders.CONTENT_DISPOSITION,
        "attachment; filename=" + "export_build" + "_"
                + date.getTime() + ".csv");
printWriter.write(stringBuilder.toString());

Make sure to write the content after printing the header to ensure content is packaged in a file properly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top