Force File Download with ASP.NET (C#)
Today's Browsers are capable of opening many different types of files. For example, if you click on a link to MP3 file, most Browsers will play it within the Browser. But sometimes you may want to provide a 'Download File' link, which will force the Browser to save the target file on user's computer even if the Browser is capable of opening it. Recently I worked on a Website that offered a download option to music files.
In addition to forcing download of a File, you may also want to perform tasks like verifying if the user has access to the File, or keep a count of number of times a File has been downloaded.
The simple trick to force download of a File is adding a HTTP header called content-disposition=attachment. You can also add a file name to this header to suggest a FileName for the Downloaded File.
Here is an ASP.NET example code:
Author: Abu Haider (http://www.haiders.net)
Adds Extension Method "ForceDownload" to HttpResponse class
Requires: ASP.NET 3.5
Drop this in App_Code
public static class HttpExtensions
//Forces Download/Save rather than opening in Browser//
public static void ForceDownload(this HttpResponse Response, string virtualPath, string fileName)
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
Response.ContentType = "";
The example above is an Extension method for HttpResponse, and will work for ASP.NET 3.5 onwards. If you add this class to App_Code, a new method named 'ForceDownload()' will be available on the Response object. Here is an example you can use anywhere in an ASP.NET Page (Page_Load Event, for example):
Calling this method will end the response after sending the File to client.
For ASP.NET 2.0, you can use the body of the Extension method and add it to Page_Load Event directly.
The above Extension Method simply clears the CotnentType header. This is to keep the method generic. If you would like to specify ContentType for the target File, you can add another Parameter to the method and assign it to the ContenType header instead of clearing it. ContentType header is used by the Browser to understand what type of data is being received so they can display it properly or use an associated program to open it. Clearing the ContentType does work in this case since we do not want the Browser to try and open the File with an associated program, but simply save it to disk.
My observation is that if there is no ContentType present, IE uses the file extension to uderstand the content.
Posted on November 25, 2008 05:45 by Haider