简体   繁体   中英

JSP: save a file on client without storing it on server

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!

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.

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.

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