Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome appends hyphen "-" to the downloaded CSV file

Tags:

java

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.

like image 503
saranya Avatar asked Jun 30 '11 06:06

saranya


2 Answers

I'm seeing two things:

  1. You shouldn't have a space after filename= in your Content-Disposition.
  2. I've never used quotes around the filename; I don't think you're meant to. I don't see anything about using quotes in the RFC, so I'd get rid of them.

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.)

like image 110
T.J. Crowder Avatar answered Sep 23 '22 08:09

T.J. Crowder


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.

like image 42
gorlok Avatar answered Sep 21 '22 08:09

gorlok