Tuesday, 19 February 2008

File Download In Spring

In order to implement a file download in Spring, the key is returning null instead of a ModelAndView object. This controller that I created below is specifically for text/ascii data. You'd need to change the content type appropriately in order to download other file types.

public class DownloadController implements Controller {
/*
* Spring dependency injection
*/
private XService xService;

public void setxService(
XService xService) {
this.xService = xService;
}

public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
String idStr = request.getParameter("id");
if (idStr != null) {
long id = Long.parseLong(idStr);
String data = xService.getData(id);
doDownload(request, response, data, "file" + idStr + ".xml");
}
return null;
}

private void doDownload(HttpServletRequest request,
HttpServletResponse response, String data, String filename)
throws IOException {
int length = data.length();
ServletOutputStream op = response.getOutputStream();

response.setContentType("text/plain");
response.setContentLength(data.length());
response.setHeader("Content-Disposition",
"attachment; filename=\"" + filename + "\"");

byte[] bbuf = data.getBytes();
op.write(bbuf, 0, length);
op.flush();
op.close();
}
}
blog comments powered by Disqus