My code works for IE and FF. In Chrome, the browser appends "-" hyphen to the start and end of the file name, thus making it unable to recognize the file type. On renaming the file while saving as csv makes it open in Excel in a single cell but I want a solution to handle it in the code side. It seems difficult.
Below is my code:
//fileName = xxxx.csv
response.setContentType("application/download");
response.setHeader("Cache-Control", "public");
response.setHeader("Content-Type", "application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename= \"" + fileName + "\"");
Note: I searched many blogs but didn't find the solution for Chrome.
I'm seeing two things:
filename=
in your Content-Disposition
.I expect you're seeing a hyphen because Chrome is replacing either the space or (more likely) the quotes with hyphens because it considers the quotes invalid characters for the filename on your OS.
FWIW, my working Content-Disposition
headers look like this:
Content-Disposition: attachment;filename=someFileName.csv
Off-topic: Re your statement:
My code works for IE and FF. In Chrome, the browser appends "-" hypen to the start and end of the file name, thus making it unable to recognize the file type.
Browsers should (and mostly do) recognise file type by the MIME type, not the file extension. You might want to set Content-Type
to text/csv
rather than application/octet-stream
. (Of course, if you're talking about what the OS does with the file later, that's another thing.)
It's a bug/feature of Chrome. https://code.google.com/p/chromium/issues/detail?id=69939
Looks like Chrome considers the quotes part of the filename but realizes that they are valid characters for a filename and so converts them to hyphens.
RFC2183 defines the Content-Disposition header but does not say what should happen if the server encloses the filename in quotes.
http://www.ietf.org/rfc/rfc2183.txt (from 1st comment)
You must remove quotes from filename part of the Content-Disposition. I'm not sure what happens with blanks in filenames without quotes. That needs to be tested.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With