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="" version="2.1">
<!-- Download.jspx
 - Copyright (c) 2012,, All Rights Reserved.
< session="false" import="*" />
   String p = request.getQueryString();
   boolean ok = true;
   ok = p!=null;
   if (ok) {
      if (p.indexOf(".html")>-1) {
      } else if (p.indexOf(".gif")>-1) {
      } else if (p.indexOf(".pdf")>-1) {
      } else if (p.indexOf(".doc")>-1) {
      } else {
         ok = false;
   if (ok) {
         "attachment; filename="+p);
      try {
         String v = application.getRealPath(p);
         int l = (int) new File(v).length();
         byte[] b = new byte[l];
         FileInputStream f = new FileInputStream(v);;
         ServletOutputStream o = response.getOutputStream();
      } catch (Exception e) {
         ok = false;
   if (!ok) {

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

 About This Book

 JSP (JavaServer Pages) Overview

 Tomcat 7 Installation on Windows Systems

 JSP Scripting Elements

 Java Servlet Introduction

 JSP Implicit Objects

 Syntax of JSP Pages and JSP Documents

 JSP Application Session

 Managing Cookies in JSP Pages

 JavaBean Objects and "useBean" Action Elements

Managing HTTP Response Header Lines

 What Is HTTP Response?

 HTTP Response Header Lines

 Controlling Response Header Lines

 Viewing 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

 Performance of JSP Pages

 EL (Expression Language)

 Overview of JSTL (JSP Standard Tag Libraries)

 JSTL Core Library

 JSP Custom Tags

 JSP Java Tag Interface

 Custom Tag Attributes

 Multiple Tags Working Together

 File Upload Test Application

 Outdated Tutorials


 PDF Printing Version