Using Open CSV to Send files from ServletOutputStream
Question
I have parsed a JSON Object that was sent to my TOMCAT server using POST and turned it into a CSV file. I would like to send the CSV file back to the user. I am confused about how to send the file back because all the examples I have seen reference an actual file that is stored on the server - my file is built in memory and doesn't actually reference a file/file descriptor as far as I can tell.
//The doPost method has already generated the String[] - I then call generateCSV
protected void generateCSV(ArrayList<String[]> data, ServletOutputStream out,
HttpServletResponse response)
{
try{
BufferedWriter buff = new BufferedWriter(new OutputStreamWriter(out));
CSVWriter writer = new CSVWriter(buff);
writer.writeAll(data);
writer.close();
sendFile(response, out);
}catch(IOException | ServletException e){
e.printStackTrace();
}
}
protected void sendFile(HttpServletResponse response, ServletOutputStream outstream)throws ServletException, IOException
{
response.setContentType("application/octet-stream");
outstream.flush();
outstream.close();
}
Solution
What do you have to do to send a file to the user from a servlet?
- Set the content-type.
- Write out the bytes.
Seems to me you are doing this, but in the wrong order. Also, rather than using application/octet-stream you might want to actually tell the browser this is CSV. You might also want to give it a filename.
response.setContentType("text/csv");
response.setHeader("Content-Disposition","filename=whatever.csv");
BufferedWriter buff = new BufferedWriter(new OutputStreamWriter(out));
CSVWriter writer = new CSVWriter(buff);
writer.writeAll(data);
writer.close();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow