--
///
/// 输出硬盘文件,提供下载 支持大文件、续传、速度限制、资源占用小
///
/// Page.Request对象
/// Page.Response对象
/// 下载文件名
/// 带文件名下载路径
/// 每秒允许下载的字节数
///
public bool ResponseFile(HttpRequest MyRequest, HttpResponse MyResponse, string MyFileName, string MyFullPath, long MySpeed)
{
try
{
FileStream myFile = new FileStream(MyFullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
BinaryReader br = new BinaryReader(myFile);
try
{
MyResponse.AddHeader("Accept-Ranges", "bytes");
MyResponse.Buffer = false;
long fileLength = myFile.Length;
long startBytes = 0;
int pack = 10240; //10K bytes
int sleep = (int)Math.Floor(1000.0 * pack / MySpeed) + 1;
if (MyRequest.Headers["Range"] != null)
{
MyResponse.StatusCode = 206;
string[] range = MyRequest.Headers["Range"].Split(new char[] { '=', '-' });
startBytes = Convert.ToInt64(range[1]);
}
MyResponse.AddHeader("Content-Length", (fileLength - startBytes).ToString());
if ((startBytes != 0))
{
MyResponse.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
}
MyResponse.AddHeader("Connection", "Keep-Alive");
MyResponse.ContentType = "application/octet-stream";
MyResponse.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(MyFileName, System.Text.Encoding.UTF8));
br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
int maxCount = (int)Math.Floor(1.0*(fileLength - startBytes) / pack) + 1;
for (int i = 0; i <= maxCount; i++)
{
if ((MyResponse.IsClientConnected))
{
MyResponse.BinaryWrite(br.ReadBytes(pack));
System.Threading.Thread.Sleep(sleep);
}
else
{
i = maxCount;
}
}
}
catch
{
return false;
}
finally
{
br.Close();myFile.Close();
}
}
catch
{
return false;
}
return true;
}
直接调用就行了.如
ResponseFile(Request, Response, "MyText.txt", @"D:\testtable.txt", 200 * 1024);
沒有留言:
張貼留言