Sending Files as Downloads

This section provides a tutorial example on how to send files to the Web browser as downloads using the Content-disposition header line.

Another way of sending files to the browser is via attachment. The following ASP page shows you how to do this:

<script language="vbscript" runat="server">
'  download.asp
'  Copyright (c) 2002 by Dr. Herong Yang
   p = request.ServerVariables("QUERY_STRING")
   ok = Len(p)>0
   if (ok) then
      if (InStr(p,".html")>0) then
         contentType = "text/html"
      elseif (InStr(p,".gif")>0) then
         contentType = "image/gif"
      elseif (InStr(p,".pdf")>0) then
         contentType = "application/pdf"
      elseif (InStr(p,".doc")>0) then
         contentType = "application/msword"
      else
         ok = false
      end if
   end if
   r = request.ServerVariables("APPL_PHYSICAL_PATH")
   filePath = r & p
   if (ok) then
      response.Buffer = True
      response.Clear
      response.ContentType = contentType
      response.AddHeader "Content-disposition", _
         "attachment; filename="&p
      set objStream = Server.CreateObject("ADODB.Stream")
      objStream.Open
      objStream.Type = 1 'binar type?
      objStream.LoadFromFile filePath
      response.BinaryWrite objStream.Read
      objStream.Close
      response.Flush
      response.End
   else
      response.Write "<html><body>Error:<br/>"
      response.Write "ApplPhysicalPath = ("&r&")<br/>"
      response.Write "QueryString = ("&p&")<br/>"
      response.Write "</body></html>"
      response.End
   end if
</script>

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.asp?hello.pdf, you will see IE prompting you to save the attachment instead of calling Adobe Reader to display the data.

Last update: 2002.

Table of Contents

 About This Book

 ASP (Active Server Pages) Introduction

 IIS (Internet Information Services) 5.0

 MS Script Debugger

 VBScript Language

 ASP Built-in Run-time Objects

 ASP Session

 Creating and Managing Cookies

 Managing Sessions with and without Cookies

 scrrun.dll - Scripting Runtime DLL

Managing Response Header Lines

 HTTP Response Syntax

 HTTP Response Header Lines

 Controlling Response Header Lines

 Viewing Response Header Lines

 Response Header Lines for Static Files

 Controlling Response Header Line Example

 Sending Binary Files to Browsers

Sending Files as Downloads

 Calculation Speed and Response Time

 ADO (ActiveX Data Object) DLL

 Working with MS Access Database

 Guest Book Application Example

 References

 PDF Printing Version