10

I have tried everything I can think of. I have changed the mime type 100 times. Changed the headers 400 times. I've looked through stack over flow a dozen times. This works fine in Chrome. Soon as I go to download in Firefox it thinks it's a xlsx file, or a binary file. It even opens as an xlsx but it doesn't think it's a csv so the columns aren't seperated. If I save the file(instead of just hit open) it doesn't even put the extension on. I haven't even got to IE yet so this is kind of worrying me.

    mime mapping
   <mime-mapping>
        <extension>csv</extension>
        <mime-type>application/vnd.ms-excel</mime-type>
    </mime-mapping> 

I've tried text/csv, application/csv, application/binary, application/octet-stream.

public void doDownloadFile() {

            PrintWriter out = null;

            try {

                String fileName = selectedPkgLine.getShortname() + ".csv";

                HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
                HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();

                response.setHeader("Pragma", "public");
                response.setHeader("Expires", "0");
                response.setContentType(request.getServletContext().getMimeType(fileName));
                response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
                response.setHeader("Content-disposition", "attachment; filename=" + fileName + "");
                response.setHeader("Content-Transfer-Encoding", "binary");

                out = response.getWriter();
                CSVWriter writer = new CSVWriter(out);

                List<PkgLoad> pkgLoadList = pkgLoadService.findBetweenDates(selectedPkgLine, startDate, endDate);

                List<String[]> stringList = new ArrayList<String[]>();
                stringList.clear();

                String[] header = {
                    "pkg_load_id",
                    "time_stamp",
                    "ounces",
                    "revolutions",
                    "wrap_spec_id",
                    "pkg_line_id"
                };

                stringList.add(header);

                for (PkgLoad pkgLoad : pkgLoadList) {

                    String[] string = {
                        pkgLoad.getPkgLoadId().toString(),
                        pkgLoad.getTimeStamp().toString(),
                        pkgLoad.getOunces().toString(),
                        pkgLoad.getRevolutions().toString(),
                        pkgLoad.getWrapSpecId().getWrapSpecId().toString(),
                        pkgLoad.getPkgLineId().getPkgLineId().toString()
                    };
                    stringList.add(string);
                }

                response.setHeader("Content-length", String.valueOf(stringList.size()));


                writer.writeAll(stringList);
                out.flush();

            } catch (IOException ex) {
                Logger.getLogger(ViewLines.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                out.close();
            }
        }

Thanks for any help.

Safari, Opera and Chrome work fine. Haven't tried IE.

****EDIT****

Ok this entire time it was a spacing issue. My file name was "file name.csv" and this works in every browser except firefox. Soon as I put my file name to "filename.csv with no spaces it downloaded it find. I didn't notice that when it was downloading it was only downloading the first part of the name before the space. Good luck!

Drew H
  • 4,699
  • 9
  • 57
  • 90
  • 3
    You should try it with IE and see what result you get there. Maybe that tells you more about the problem you have with Firefox. – AudioDroid Mar 01 '11 at 14:53
  • Note that the `` is only been used when the resource is been served from public webcontent by a direct link/call or when you use `ServletContext#getMimeType()`. It is irrelevant in this particular purpose where you serve the response and set the `Content-Type` header yourself. – BalusC Mar 01 '11 at 15:10
  • Yes I understand. I was just trying whatever I could do. This particular code works in IE8. It sees it as a csv and I can save it and open it. I don't know what is wrong with firefox. – Drew H Mar 01 '11 at 15:15

6 Answers6

6

I had the same issue in PHP and found adding double quotes for the file name fixes the problem.

 response.setHeader("Content-disposition", "attachment; filename=\"" + fileName + \"");
Oharrington
  • 61
  • 1
  • 1
5

The content type text/csv is correct, but you should also add an charset encoding:

response.setHeader("Content-type: text/csv; charset=utf-8");

But what the hell is this:

response.setHeader("Content-Transfer-Encoding", "binary");
response.setHeader("Content-length", String.valueOf(stringList.size()));

Remove that headers! The content length is in bytes. Do not try to calculate it by yourself. It is definitly wrong in this example! A Mime-Type with major type text is not binary!

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Arne Burmeister
  • 20,046
  • 8
  • 53
  • 94
  • Still does not work. Firefox keeps stripping the csv off the end. IE8 works in this case. If I change the content-type to .xls application/excel .xls application/vnd.ms-excel .xls application/x-excel .xls application/x-msexcel it puts an xls or xlsx on the end. – Drew H Mar 01 '11 at 15:21
  • Please [check this](http://stackoverflow.com/questions/39848019/why-php-script-does-not-generate-csv-file-in-firefox/39848402) Need help – Ayaz Ali Shah Oct 04 '16 at 10:33
4

Ok this entire time it was a spacing issue. My file name was "file name.csv" and this works in every browser except firefox. Soon as I put my file name to "filename.csv with no spaces it downloaded it find. I didn't notice that when it was downloading it was only downloading the first part of the name before the space.

In the future make sure the filename has a single quote around it in the header. This will allow Firefox to download it correctly(without stripping off anything past the space) if you need a space the file name.

Good luck!

Drew H
  • 4,699
  • 9
  • 57
  • 90
  • 1
    Anybody coming to this issue now: see http://kb.mozillazine.org/Filenames_with_spaces_are_truncated_upon_download. The real issue is that you should have Content-Disposition: attachment; filename="filename with spaces". – Nate Bundy Sep 16 '13 at 19:13
  • @NateBundy's comment is correct. You have escape double quotes around the filename if your header is in a double quoted string. – Jason H Jan 07 '14 at 16:25
  • thank you for the post, it helped to solve an issue with firefox [here](http://stackoverflow.com/a/32373057/2218697) is the solution – Shaiju T Sep 03 '15 at 10:29
1

Response.AddHeader("content-disposition", string.Format("attachment;filename=\"{0}\"", fileName)); Response.ContentType = "text/csv; charset=utf-8";

1

Add the content-type header with value text/csv

response.setHeader("Content-type: text/x-csv");
emeraldjava
  • 10,894
  • 26
  • 97
  • 170
  • 2
    `text/csv` should also suffice. – Matt Ball Mar 01 '11 at 15:00
  • Doesn't work. Same thing. Firefox sees it as a filename with no extension. If I add application/vnd.ms-excel as the content type it sees it as an excel(xlsx) file even though its a .csv file. – Drew H Mar 01 '11 at 15:06
0

I am not expert in Java/JSP but are you sure this is correct for text/csv?
response.setHeader("Content-Transfer-Encoding", "binary");
Did you try commenting out this? In PHP I will simply echo/print the CSV preceded with headers content-type headers and disposition type.

Kumar
  • 5,038
  • 7
  • 39
  • 51