JSP Tutorials - Herong's Tutorial Examples - Version 4.03, by Dr. Herong Yang
Returning Attachments for Web Download
This section provides a tutorial example on how to return back non-HTML response body as attachments to trigger Web browser to start file download processes.
Another way of sending non-HTML data to the client is via attachment. The following JSP will show you how to do this:
<?xml version="1.0"?> <jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1"> <!-- Download.jspx - Copyright (c) 2012, HerongYang.com, All Rights Reserved. --> <jsp:directive.page session="false" import="java.io.*" /> <jsp:scriptlet> String p = request.getQueryString(); boolean ok = true; ok = p!=null; if (ok) { if (p.indexOf(".html")>-1) { response.setContentType("text/html"); } else if (p.indexOf(".gif")>-1) { response.setContentType("image/gif"); } else if (p.indexOf(".pdf")>-1) { response.setContentType("application/pdf"); } else if (p.indexOf(".doc")>-1) { response.setContentType("application/msword"); } else { ok = false; } } if (ok) { response.setHeader("Content-disposition", "attachment; filename="+p); try { String v = application.getRealPath(p); int l = (int) new File(v).length(); response.setContentLength(l); byte[] b = new byte[l]; FileInputStream f = new FileInputStream(v); f.read(b); ServletOutputStream o = response.getOutputStream(); o.write(b,0,l); o.flush(); o.close(); f.close(); } catch (Exception e) { ok = false; } } if (!ok) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); } </jsp:scriptlet> </jsp:root>
In this page, another header line, "Content-disposition", is added to the response, in which I am telling the client program that the entity data is an attachment, with file name specified.
Now try to use IE to request: http://localhost:8080/Download.jsp?hello.pdf, you will see IE prompting you to save the attachment instead of calling Adobe Reader to display the data when using GetFile.jspx JSP page.
Last update: 2012.
Table of Contents
JSP (JavaServer Pages) Overview
Tomcat 7 Installation on Windows Systems
Syntax of JSP Pages and JSP Documents
JavaBean Objects and "useBean" Action Elements
►Managing HTTP Response Header Lines
Controlling Response Header Lines
Response Header Lines of Static Files
Response Header Lines Controlled by "page" Directive
Response Header Lines Controlled by response Object
Accessing File System from JSP Pages
Returning non-HTML Response Body
►Returning Attachments for Web Download
Non-ASCII Characters Support in JSP Pages
Overview of JSTL (JSP Standard Tag Libraries)