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:
- What if my data size (to be downloaded in file) increases number of characters string can hold?
- Is there a way to move method call to database outside doGet function?
- How do I start file download before data is completely fetched from database or written in response?