简体   繁体   中英

java generate dynamic csv file for download

I have written a servlet that will return a csv file (dynamically generated) to the user to download. However the client is not able to see the file size which means they receive no progress indicator.

I have this code

protected void doGet(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  try {
   String csv = getCsv();

   resp.setContentType("text/csv");
   resp.setContentLength(csv.getBytes().length);
   resp.getWriter().write(csv);
  } catch (Exception e) {
   log.error("error generating feed", e);
  }
 }

thank you.

Filesize is sent in a Response Header , specifically the Content-Length header. You have to build the entire response either in memory or on disk and calculate its size and send the Content-Length header with this size for the client to know how to calculate a progress indicator. You also with some non-standard browsers ( IE ) have to set the Disposition of the file to get the Download file dialog box to pop up and process the response correctly with a progress indicator.

Try using a browser like Firefox and the 'Live HTTP Headers' extension and 'Firebug' to debug what is actually being sent back.

You don't say what browsers this isn't working in so it may be browsers specific and need additional browsers specific meta-data.

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