简体   繁体   中英

File generated by servlet not downloading

I have a servlet with an action that generates a CSV file based on parameters passed in a POST from a form. The servlet code snippet looks like this:

response.setContentType("text/csv");
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition","attachment; filename=" + filename);
PrintWriter pw = response.getWriter();
pw.println(content); // content is some CSV in a string
pw.close();

The browser (both FF and Chrome) appears to be ignoring the attachment indicator, because it changes URL to the corresponding action (eg http://myserver.com/filedownload ) and does not present a Save As dialog. I've checked the response header in Chrome, and it looks like this (edited to now show the full, "unparsed" header):

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Disposition: attachment; filename=JobTracking.csv
Content-Type: text/csv;charset=UTF-8
Content-Length: 16876
Date: Tue, 15 Jul 2014 22:32:49 GMT

..and the "Response" tab shows the content I'm writing to the response.

I'm close to my wits end, because fairly much all the examples I've looked at do it this way successfully.

You have content type and encoding swapped in your example. It should be

response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("UTF-8");

Not sure how you getting back Content-Type:application/vnd.ms-excel;charset=UTF-8 in the response though.

Edit:

Also, the correct MIME type for CSV files is text/csv and not application/vnd.ms-excel - this one is for *.xls files.

In jQuery mobile, forms are handled by Ajax by default, using data-ajax="false" solved the issue, eg

<form id="myform" action="../filedownload" method="POST" data-ajax="false">

Bit of a head-slapping moment, there :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM