1

In my jsp someone wants to export a query result to csv. Can't use frameworks. At the moment, here is the process:

  1. press button, go to servlet
  2. prepare data for csv
  3. make csv and save to server
  4. back to jsp and let them download the fresh-made file from an anchor tag.

Thing is, I' don't want to create this file on server, as I have to dispose it afterwards, but I still want to give the user the "save as" window. So, is there a way, putting for example an OutputStream object in session, to achieve this result? Thank you all!

Ema
  • 104
  • 11

2 Answers2

2

A servlet can generate any type of content. So, when you click the button to run the servlet, simply have the servlet write the file back to the client at that time. You'll need to set the Content-type header to "text/csv" (and making sure that you set encoding properly). You don't need to set the Content-Length header; the browser can deal with that.

When the servlet returns data to the browser, the user will be prompted to save the file or open it with an application.

parsifal
  • 1,645
  • 9
  • 6
1

Yes. You don't need to save the file. Just hold it in the session and send it in-memory to the OutputStream. I would trash it after a given time or after delivery in order to save memory.

Set the content type and the content disposition appropriately. This will mean that the browser interprets the output correctly and prompts your user to save it or launch the appropriate application.

See this SO answer for more details.

Community
  • 1
  • 1
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
  • sorry, can you explain me exactly what do you mean? provided I save the file in an outputstream and I set this on session, how can I access it from jsp/html? sorry if this seems trivial, not so familiar with client-side! – Ema Jan 04 '13 at 15:02
  • Saving a file in the session could be a problem, especially a large file (and doubly-so if you have a clustered server). – parsifal Jan 04 '13 at 15:04
  • Save the data in-session in whatever form you wish, and simply render as CSV upon output. Note also parsifal's comments re clustering – Brian Agnew Jan 04 '13 at 15:27