Firefox will not download this file as a CSV - java

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!

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 + \"");

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!

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!

Add the content-type header with value text/csv
response.setHeader("Content-type: text/x-csv");

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

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.

Related

httpServletResponse behavior in chrome and firefox

I have a controller method in charge of an excel download:
#RequestMapping(value = "/report/user", method = RequestMethod.GET)
public void getUserReport(#RequestParam(value = "name", required = false) String user,
#RequestParam(value = "startdate", required = false) String startDate,
#RequestParam(value = "enddate", required = false) String endDate,
HttpServletResponse response) {
List<Survey> userSurveys = surveyService.findUserSurveys(user, startDate, endDate);
String userFileName = nameService.getUserFileName(user, startDate, endDate);
Workbook userExcelReport = excelReportGenerator.createUserExcelReport(userSurveys);
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "attachment; filename=" + userFileName + ".xlsx");
try {
userExcelReport.write(response.getOutputStream());
} catch (IOException e) {
logger.error("The excel workbook could not write to the outputStream ", e);
}
}
as you can see this controller mapping is tanking a excel workbook (done in apache poi) and setting the header and content type, in google chrome this works perfectly but in firefox the file is downloaded as a "file" with no extension (but the data is correct as if i open the file with excel all is there) and the name is built wrong, as in chrome this works completely fine i assume there is something wrong the way the response works in firefox, anyone has idea what could i be doing wrong?
example of downloaded files trough firefox
example of downloads using chrome
According RFC 6266 the filename value is either a token or a quoted-string.
A token must not contain separators. But white space is a separator. So you must using a quoted-string.
So try
response.setHeader("Content-Disposition", "attachment; filename=\"" + userFileName + ".xlsx\"");
Please check this way to sent content type in response. It works for me.
resp.setContentType( "application/octet-stream" );

Download CSV file via Rest

Using OpenCSV, I can successfully create a CSV file on disc, but what I really need is to allow users download the CSV with a download button, I don't need to save on disk, just download. Any ideas?
#GET
#Path("/downloadCsv")
public Object downloadCsv() {
CSVWriter writer;
FileWriter wr;
//Or should I use outputstream here?
wr= new FileWriter("MyFile.csv");
writer = new CSVWriter(wr,',');
for (Asset elem: assets) {
writer.writeNext(elem.toStringArray());
}
writer.close();
}
EDIT: I do NOT want to save/read file on disc EVER
To force "save as", you need to set the content disposition HTTP header in the response. It should look like this:
Content-Disposition: attachment; filename="whatever.csv"
It looks like you're using JAX-RS. This question shows how to set the header. You can either write the CSV to the HTTP response stream and set the header there or return a Response object like so:
return Response.ok(myCsvText).header("Content-Disposition", "attachment; filename=" + fileName).build();
You do not need to write to a File object in the middle of this process so can avoid writing to disk.
First, you code cannot be compiled, right? Method downloadCsv() declares return type Object but does not return anything.
I'd change the declaration to String downloadCsv() and return the content of CSV as string. To do this use StringWriter instead of FileWriter and then say return wr.toString().
The only thing that is missing here is content type. You annotate your method as #Produces({"text/csv"}).
I think, that's it.
response.setHeader("Content-Disposition", "attachment; filename=" + filename + ".csv");
response.setContentType("text/csv");
OutputStreamWriter osw = new OutputStreamWriter(response.getOutputStream(), "UTF-8");
List<String[]> result = iSmsExportService.csvExport(columnNames);
CSVWriter csvWriter = new CSVWriter(osw, ';');
csvWriter.writeAll(result);
csvWriter.flush();
csvWriter.close();
Downloading of CSV file has started after this.

Create and download CSV file in a Java servlet

I am working on Java ExtJS application in which I need to create and download a CSV file.
On clicking a button I want a CSV file to be downloaded to a client's
machine.
On buttons listener I am calling a servlet using AJAX. There I am
creating a CSV file.
I don't want the CSV file to be saved in the server. I want the file should be created dynamically with a download option. I want the contents of a file to be created as a string and then I will serve the content as file in which it will open as download mode in browser (this I have achieved in other language, but not sure how to achieve it in Java).
Here is my code only to create a CSV file, but I really don't want to create or save CSV file if I can only download the file as CSV.
public String createCSV() {
try {
String filename = "c:\\test.csv";
FileWriter fw = new FileWriter(filename);
fw.append("XXXX");
fw.append(',');
fw.append("YYYY");
fw.append(',');
fw.append("ZZZZ");
fw.append(',');
fw.append("AAAA");
fw.append(',');
fw.append("BBBB");
fw.append('\n');
CSVResult.close();
return "Csv file Successfully created";
} catch(Exception e) {
return e.toString();
}
}
Can any one help me on this.
Thanks
I got the solution and I am posting it below.
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
response.setContentType("text/csv");
response.setHeader("Content-Disposition", "attachment; filename=\"userDirectory.csv\"");
try
{
OutputStream outputStream = response.getOutputStream();
String outputResult = "xxxx, yyyy, zzzz, aaaa, bbbb, ccccc, dddd, eeee, ffff, gggg\n";
outputStream.write(outputResult.getBytes());
outputStream.flush();
outputStream.close();
}
catch(Exception e)
{
System.out.println(e.toString());
}
}
Here we don't need to save / store the file in the server.
Thanks
First of all you need to get the HttpServletResponse object so that you can stream a file into it.
Note : This example is something I Wrote for one of my projects and it works.Works on Java 7.
Assuming you got the HttpServletResponse you can do something like this to stream a file. This way the file will be saved into clients' machine.
public void downloadFile(HttpServletResponse response){
String sourceFile = "c:\\source.csv";
try {
FileInputStream inputStream = new FileInputStream(sourceFile);
String disposition = "attachment; fileName=outputfile.csv";
response.setContentType("text/csv");
response.setHeader("Content-Disposition", disposition);
response.setHeader("content-Length", String.valueOf(stream(inputStream, response.getOutputStream())));
} catch (IOException e) {
logger.error("Error occurred while downloading file {}",e);
}
}
And the stream method should be like this.
private long stream(InputStream input, OutputStream output) throws IOException {
try (ReadableByteChannel inputChannel = Channels.newChannel(input); WritableByteChannel outputChannel = Channels.newChannel(output)) {
ByteBuffer buffer = ByteBuffer.allocate(10240);
long size = 0;
while (inputChannel.read(buffer) != -1) {
buffer.flip();
size += outputChannel.write(buffer);
buffer.clear();
}
return size;
}
}
What this does is, get an inputstream from your source file and write that stream into the outputstream of the HttpServletResponse. This should work since it works perfectly for me. Hope this helps. Sorry for my bad English.
I would like add something to the answer by gaurav. I recently had to implment this functionality in a project of mine and using javascript was out of the question becuase we had to support IE 9. What is the problem with IE 9?
(Export to CSV using jQuery and html), see the second answer in the link.
I needed an easy way to convert a ResultSet of a database query to a string which represent the the same data in CSV format. For that I used http://opencsv.sourceforge.net/ which provided an easy way to get a String ot of the ResultSet, and the rest is as above answer did it.
THe examples in the project soruce folder give good examples.

How do I return a zip file to the browser via the response OutputStream?

In this situation, I have created a zip file containing search result files, and am trying to send it to the user. Here is the chunk of code I am currently trying to use.
File[] zippable = new File[files.size()];
File resultFile = ZipCreator.zip(files.toArray(zippable), results);
InputStream result = new FileInputStream(resultFile);
IOUtils.copy(result, response.getOutputStream());
However, this currently doesn't work quite right. Instead of returning the zip file that I have created, it returns an html file. If I manually change the file extension afterwards, I can see that the contents of the file are still the search results that I need. So the problem just lies in returning the proper extension to the response.
Does anyone have any advice for this situation?
You need to set the Content-Type response header to the value application/zip (or application/octet-stream, depending on the target browser). Additionally, you may want to send additional response headers indicating attachment status and filename.
You need to set the content type header to application/octet-stream prior to streaming the results. Depends on what implementation of response you are using on how you actually do this.
Here is some working code, just in case anyone needs it:
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
// The zip file you want to download
File zipFile = new File(zipsResourcesPath + zipFileName);
response.setContentType("application/zip");
response.addHeader("Content-Disposition", "attachment; filename=" + zipFileName);
response.setContentLength((int) zipFile.length());
try {
FileInputStream fileInputStream = new FileInputStream(zipFile);
OutputStream responseOutputStream = response.getOutputStream();
int bytes;
while ((bytes = fileInputStream.read()) != -1) {
responseOutputStream.write(bytes);
}
} catch (IOException e) {
logger.error("Exception: " + e);
}
}
And the HTML:
<a class="btn" href="/path_to_servlet" target="_blank">Download zip</a>
Hope this helps!
So I found a hack for this : ) Just add ".zip" in your filename and set your content type as application/zip. Works like a charm.
response.setContentType("application/zip");
String licenseFileName = eId;
response.setHeader("Content-disposition", "attachment; filename=\"" + licenseFileName +".zip");

iText generated PDF not shown correctly in Chrome

I am using the iText library in Java to generate a pdf file. The idea is that a user fills in some information and that when the user clicks on the generate button the pdf is shown in a new tab in the browser. Now I have stumbled upon some problems doing this, which are :
- the URL does not change, so instead of /application/user.pdf I get /application/dashboard.xhtml
- I can save the pdf file in all browsers except for Chrome.
Please note that I don't want to save it on disc but simply show the pdf in the browser so the user can choose if he wants to save it.
Here is the code that I use to generate my pdf :
public static void createPdf(User user, byte languageNumber, HttpServletResponse response) {
Document document = new Document();
try {
/* PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream("c://" + user.getUsername() + "_" + languageCode + ".pdf"));*/
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter.getInstance(document, baos);
document.addTitle("Your CV");
document.addSubject("This is your CV");
document.addKeywords("CV");
document.addAuthor(user.getUsername());
document.open();
document.add(
new Paragraph(user.getPersonalInformation().getFirstname() + " " + user.getPersonalInformation().getLastname()));
document.close();
// setting some response headers
response.setHeader("Expires", "0");
response.setHeader("Cache-Control",
"must-revalidate, post-check=0, pre-check=0");
response.setHeader("Pragma", "public");
// setting the content type
response.setContentType("application/pdf");
response.setContentLength(baos.size());
//ServletOutputStream out = response.getOutputStream();
OutputStream out = response.getOutputStream();
baos.writeTo(out);
out.flush();
out.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
*This method is behind a button on my JSF page *
public String exportPdf() {
user = userService.retrieveLoginUser();
FacesContext context = FacesContext.getCurrentInstance();
try {
Object response = context.getExternalContext().getResponse();
if (response instanceof HttpServletResponse) {
HttpServletResponse hsr = (HttpServletResponse) response;
PdfCreator.createPdf(user, selectLanguage, hsr);
//Tell JSF to skip the remaining phases of the lifecycle
context.responseComplete();
}
return "../" + user.getUsername() + ".pdf";
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Used technologies :
- JSF 2.0
- Facelets
- iText
Thanks in advance :D
The way that I have achieved this in the past is by creating a seperate Servlet to serve PDF documents directly. In the web.xml file you would specify the servlet mapping to *.pdf.
What you can do then is rather than override the FacesServlet response bytes to server the PDF file you just redirect the response to filename.pdf, passing needed parameters in the URL.
Your PDF servlet can actually do the work of building the necessary PDF, it will open in a seperate tab and the URL will match the response redirect.
Does chrome open the PDF and then not render it correctly? In that case, please open an issue at http://new.crbug.com and attach an example PDF file that shows the problem. Reply with the issue number here.

Categories

Resources