Java: Download Dialog for the Browser

August 31, 2014

If ever you’ve encountered this requirement where you need to make the download dialog from the browser show up when a user is downloading a file from your Java-backed website, the solution is this:

response.setHeader("Content-Disposition", String.format("attachment; filename=\"sample_file.csv\""));
response.getWriter().write("This is a test file.");

You simply need to set the Header and Content Type. I was handling a bug last week, wherein the download dialog was working intermittently. After looking at the code, it was because the Content Type and Header were set AFTER the response was written. Shifting the write response part after setting those two attributes fixed the issue.

blog comments powered by Disqus