How to force the download dialog box to appear
Today someone asked me how to force the "File Download" dialog box to appear in Internet Explorer. I thought I knew the answer but I learned a new trick.
They have a directory structure like this:
The files should by default open the browser but they wanted to add a "download" link as well for people who don't know how to right click and choose "Save As…".No problem, I thought, and pointed them to How To Raise a "File Download" Dialog Box for a Known MIME Type and gave them some old code I had laying around:
sFile = server.MapPath(Request("dir") & Request("fileName"))
set binaryData = Server.CreateObject("ADODB.Stream")
binaryData.Type = 1 'binary
Response.AddHeader "Content-Disposition","attachment; filename=" & Request("fileName")
set binaryData = nothing
It sets the "Content-Disposition" header to attachment which instructs the browser to open the download window. This solution is OK when you download contents from a DB but I don't like it when the contents come from the file system as the script accepts a directory and file name in input. You have to be very careful so the page is not used to download contents like the source code of the ASP pages or other files outside the intended directory.
Then I decided to try the custom http header support in IIS 6.0:
- Create a new virtual directory, for example /download
- Point it to the directory you want to enable downloads for (/products in my case).
- Go to the "HTTP Headers" tab in the properties of the new virtual directory
- Add a new custom HTTP header. Name=Content-Disposition and Value=attachment
We changed the index page so it links to /download/products/images/file1.jpg as well as /products/images/file1.jpg and it works like a charm. The first link opens the “File Download“ dialog box whereas the second link opens the file inside the browser. This approach has several benefits over the ASP based approach:
- Security. You cannot trick the ASP file to download files outside the products directory
- Performance. It is faster than running an ASP script and you don't tie up valuable ASP script threads.
- Faster and simpler to implement and deploy