0

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();
}

1 Answer 1

2

What do you have to do to send a file to the user from a servlet?

  1. Set the content-type.
  2. 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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.