0

My application requires a download button in UI, which on clicking enables user to download data as csv file. I have working implementation to do this, where server side code is this :

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    int BUFFER = 1024;
    resp.setContentType("application/octet-stream");
    resp.setHeader("Content-Disposition:", "attachment;filename=" + "\"" + "sample_csv_filename" + ".csv\"");
    resp.setBufferSize(BUFFER);
    StringBuilder str = new StringBuilder();
    String comma = "";
    List<HashMap<String,Object>> tempList = //method call to get from database
    for(HashMap<String,Object> mp : tempList){comma = "";
         str.append("\n");
         for(String attr://Array of key values in HashMap){
                str.append(comma);
                comma = ",";
                str.append((String)mp.get(attr));
        }
    }
    byte bytes[] = str.toString().getBytes();
    resp.getOutputStream().write(bytes);
    resp.setContentLength(bytes.length);
    }

I have following questions/problems with this implementation:

  1. What if my data size (to be downloaded in file) increases number of characters string can hold?
  2. Is there a way to move method call to database outside doGet function?
  3. How do I start file download before data is completely fetched from database or written in response?
RJN_WLY
  • 335
  • 1
  • 4
  • 18
  • About the data size : http requests & responses can be gzip encoded. What do you mean by "move method call outside doGet" ? – Ephi Aug 17 '16 at 09:55
  • About 3. : related http://stackoverflow.com/questions/685271/using-servletoutputstream-to-write-very-large-files-in-a-java-servlet-without-me – Ephi Aug 17 '16 at 09:58
  • @Ephi : move method call outside doGet, Can I call the method somewhere outside doGet and call it before doGet call, to keep data stored in servlet and save the time to download data from database when doGet is called. – RJN_WLY Aug 17 '16 at 10:40
  • Well yes of course you can, but you can't really anticipate the time when a user will need that data, so I suppose you could fetch the data at somepoints where you know it wont be changed before the next download. Actually the problem is more about how you keep that huge database in memory. – Ephi Aug 17 '16 at 11:42

0 Answers0