以下為代碼片段:
//輸出硬碟檔案,提供下載下傳支援大檔案、續傳、速度限制、資源占用小
//輸入參數_request:page.request對象,_response:page.response對象,_filename:下載下傳檔案名,_fullpath:帶檔案名下載下傳路徑,_speed每秒允許下載下傳的位元組數
//傳回是否成功
publicstaticboolresponsefile(httprequest_request,httpresponse_response,string_filename,string_fullpath,long_speed)
{
try
filestreammyfile=newfilestream(_fullpath,filemode.open,fileaccess.read,fileshare.readwrite);
binaryreaderbr=newbinaryreader(myfile);
_response.addheader("accept-ranges","bytes");
_response.buffer=false;
longfilelength=myfile.length;
longstartbytes=0;
intpack=10240;//10kbytes
//intsleep=200;//每秒5次即5*10kbytes每秒
intsleep=(int)math.floor(1000*pack/_speed)+1;
if(_request.headers["range"]!=null)
_response.statuscode=206;
string[]range=_request.headers["range"].split(newchar[]{'=','-'});
startbytes=convert.toint64(range[1]);
}
_response.addheader("content-length",(filelength-startbytes).tostring());
if(startbytes!=0)
_response.addheader("content-range",string.format("bytes{0}-{1}/{2}",startbytes,filelength-1,filelength));
_response.addheader("connection","keep-alive");
_response.contenttype="application/octet-stream";
_response.addheader("content-disposition","attachment;filename="+httputility.urlencode(_filename,system.text.encoding.utf8));
br.basestream.seek(startbytes,seekorigin.begin);
intmaxcount=(int)math.floor((filelength-startbytes)/pack)+1;
for(inti=0;i<maxcount;i++)
if(_response.isclientconnected)
_response.binarywrite(br.readbytes(pack));
thread.sleep(sleep);
else
i=maxcount;
catch
returnfalse;
finally
br.close();
myfile.close();
returntrue;
調用例
page.response.clear();
boolsuccess=responsefile(page.request,page.response,"filename",@"c:/download.date",1024000);
if(!success)
response.write("下載下傳檔案出錯!");
page.response.end();