// 输出硬盘文件,提供下载
// 输入参数 _request: page.request对象, _response: page.response对象, _filename: 下载文件名, _fullpath: 带文件名下载路径, _speed 每秒允许下载的字节数
// 返回是否成功
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(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((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;
}
调用例
page.response.clear();
bool success = responsefile(page.request, page.response, "filename", @"c:/download.date", 1024000);
if(!success)
response.write("下载文件出错!");
page.response.end();
中国最大的web开发资源网站及技术社区,新闻热点
疑难解答
图片精选