using system;
using system.data;
using system.configuration;
using system.web;
using system.web.security;
using system.web.ui;
using system.web.ui.webcontrols;
using system.web.ui.webcontrols.webparts;
using system.web.ui.htmlcontrols;
using system.io;
using system.threading;
/// <summary>
/// filedownload 的摘要说明
/// </summary>
public class filedownload
{
/// <summary>
/// 输出硬盘文件,提供下载 支持大文件、续传、速度限制、资源占用小
/// </summary>
/// <param name="_request">page.request对象</param>
/// <param name="_response">page.response对象</param>
/// <param name="_filename">下载文件名</param>
/// <param name="_fullpath">带文件名下载路径</param>
/// <param name="_speed">每秒允许下载的字节数</param>
/// <returns>返回是否成功</returns>
public static bool responsefile(httprequest _request, httpresponse _response, string _filename, string _fullpath, long _speed)
{
try
{
filestream myfile = new filestream(_fullpath, filemode.open, fileaccess.read, fileshare.readwrite);
binaryreader br = new binaryreader(myfile);
try
{
_response.addheader("accept-ranges", "bytes");
_response.buffer = false;
long filelength = myfile.length;
long startbytes = 0;
int pack = 10240; //10k bytes
//int sleep = 200; //每秒5次 即5*10k bytes每秒
int sleep = (int)math.floor((decimal)1000 * pack / _speed) + 1;
if (_request.headers["range"] != null)
{
_response.statuscode = 206;
string[] range = _request.headers["range"].split(new char[] { '=', '-' });
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);
int maxcount = (int)math.floor((decimal)(filelength - startbytes) / pack) + 1;
for (int i = 0; i < maxcount; i++)
{
if (_response.isclientconnected)
{
_response.binarywrite(br.readbytes(pack));
thread.sleep(sleep);
}
else
{
i = maxcount;
}
}
}
catch
{
return false;
}
finally
{
br.close();
myfile.close();
}
}
catch
{
return false;
}
return true;
}
}