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:

01/***********
02Author: Abu Haider (http://www.haiders.net)
03Nov 2008
04Adds Extension Method "ForceDownload" to HttpResponse class
05Requires: ASP.NET 3.5
06Drop this in App_Code
07/************/
08
09
10publicstaticclassHttpExtensions
11{
12
13//Forces Download/Save rather than opening in Browser//
14publicstaticvoidForceDownload(thisHttpResponse Response,stringvirtualPath,stringfileName)
15{
16
17Response.Clear();
18Response.AddHeader("content-disposition","attachment; filename="+ fileName);
19Response.WriteFile(virtualPath);
20Response.ContentType ="";
21Response.End();
22
23}
24
25}

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):

1Response.ForceDownload("~/Downloads/MyMusic.mp3","MyMusic.mp3");

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.

About ContentType

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.