Posts Tagged ‘servlets’

Presenting HttpServletResponse as file download

June 17th, 2011

The following code will present the response as a file to be download instead of being displayed in the browser. The key here is the Content-disposition header.

protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException
{
	byte[] data = null;
	// load data
 
	resp.reset();
	resp.setContentType("image/png");
	resp.setHeader("Content-disposition", "attachment; filename=image.png");
 
	final OutputStream output = resp.getOutputStream();
	output.write(data);
	output.close();
}