Address: http://www.cnblogs.com/mrray/archive/2010/12/22/1914108.html
By default, you can directly link to the address of the file to download the file. However, in some cases, the file is directly opened in the browser. For example, for the download of a TXT file, the Firefox browser opened the TXT file directly, instead of downloading the TXT file. The TXT file is actually cached by the browser.
The same is true for PDF. Generally, Adobe Reader is installed on a computer. When a browser downloads a PDF file, the browser still opens the PDF file instead of downloading the PDF file.
The followingCodeBy default, files are not allowed to be opened by the browser and files are downloaded.
Download. ashx
<% @ Webhandler Language = " C # " Class = " Download " %> Using System; Using System. Web; Using System. IO; Public Class Download: ihttphandler { Public Void Processrequest (httpcontext context) {context. response. contenttype = " Text/plain " ; String Path = context. server. urldecode (context. Request. querystring [ " Path " ]. Tostring ()); StringFilename = path. getfilename (PATH ); // File Name StringFilepath = context. server. mappath (PATH) ; // Path If (File. exists (filepath )){ // Download an object as a ghost stream Filestream FS = New Filestream (Filepath, Filemode. Open ); Byte [] Bytes = New Byte [( Int ) Fs. Length]; FS. Read (bytes, 0 , Bytes. Length); FS. Close (); context. response. contenttype = " Application/octet-stream " ; // Notify the browser to download the file instead of opening it Context. response. addheader ( " Content-Disposition " , " Attachment; filename = " +Httputility. urlencode (Filename, System. Text. encoding. utf8); context. response. binarywrite (bytes); context. response. Flush (); context. response. End ();} Else {Context. response. Write ( " File not uploaded !! " ); Context. response. End ();}} Public Bool Isreusable { Get { Return False ;}}}