您的位置:首页 > 编程语言 > ASP

ASP.NET (C#) 强制文件下载

2011-07-22 16:28 190 查看

Today'sBrowsersarecapableofopeningmanydifferenttypesoffiles.Forexample,ifyouclickonalinktoMP3file,mostBrowserswillplayitwithintheBrowser.Butsometimesyoumaywanttoprovidea'DownloadFile'link,whichwillforcetheBrowsertosavethetargetfileonuser'scomputereveniftheBrowseriscapableofopeningit.RecentlyIworkedonaWebsitethatofferedadownloadoptiontomusicfiles.

InadditiontoforcingdownloadofaFile,youmayalsowanttoperformtaskslikeverifyingiftheuserhasaccesstotheFile,orkeepacountofnumberoftimesaFilehasbeendownloaded.

ThesimpletricktoforcedownloadofaFileisaddingaHTTPheadercalledcontent-disposition=attachment.YoucanalsoaddafilenametothisheadertosuggestaFileNamefortheDownloadedFile.

HereisanASP.NETexamplecode:

01
/***********
02
Author:AbuHaider(http://www.haiders.net)
03
Nov2008
04
AddsExtensionMethod"ForceDownload"toHttpResponseclass
05
Requires:ASP.NET3.5
06
DropthisinApp_Code
07
/************/
08
09
10
public
static
class
HttpExtensions
11
{
12
13
//ForcesDownload/SaveratherthanopeninginBrowser//
14
public
static
void
ForceDownload(
this
HttpResponseResponse,
string
virtualPath,
string
fileName)
15
{
16
17
Response.Clear();
18
Response.AddHeader(
"content-disposition"
,
"attachment;filename="
+fileName);
19
Response.WriteFile(virtualPath);
20
Response.ContentType=
""
;
21
Response.End();
22
23
}
24
25
}
TheexampleaboveisanExtensionmethodforHttpResponse,andwillworkforASP.NET3.5onwards.IfyouaddthisclasstoApp_Code,anewmethodnamed'ForceDownload()'willbeavailableontheResponseobject.HereisanexampleyoucanuseanywhereinanASP.NETPage(Page_LoadEvent,forexample):

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

ForASP.NET2.0,youcanusethebodyoftheExtensionmethodandaddittoPage_LoadEventdirectly.

AboutContentType

TheaboveExtensionMethodsimplyclearstheCotnentTypeheader.Thisistokeepthemethodgeneric.IfyouwouldliketospecifyContentTypeforthetargetFile,youcanaddanotherParametertothemethodandassignittotheContenTypeheaderinsteadofclearingit.ContentTypeheaderisusedbytheBrowsertounderstandwhattypeofdataisbeingreceivedsotheycandisplayitproperlyoruseanassociatedprogramtoopenit.ClearingtheContentTypedoesworkinthiscasesincewedonotwanttheBrowsertotryandopentheFilewithanassociatedprogram,butsimplysaveittodisk.

MyobservationisthatifthereisnoContentTypepresent,IEusesthefileextensiontouderstandthecontent.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: