-
C# code
-
<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ -->
/// <summary>
/// 输出硬盘文件,提供下载 支持大文件、续传、速度限制、资源占用小
/// </summary>
/// <param name="MyRequest"> Page.Request对象 </param>
/// <param name="MyResponse"> Page.Response对象 </param>
/// <param name="MyFileName"> 下载文件名 </param>
/// <param name="MyFullPath"> 带文件名下载路径 </param>
/// <param name="MySpeed"> 每秒允许下载的字节数 </param>
/// <returns> True Or False </returns>
public static bool DownLoadFile(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 ;
}