復制代碼 代碼如下:
public static bool DownloadFile(HttpContext httpContext, string filePath, long speed)
{
bool ret = true;
try
{
#region--驗證:HttpMethod,請求的文件是否存在
switch (httpContext.Request.HttpMethod.ToUpper())
{ //目前只支持GET和HEAD方法
case "GET":
case "HEAD":
break;
default:
httpContext.Response.StatusCode = 501;
return false;
}
if (!File.Exists(filePath))
{
httpContext.Response.StatusCode = 404;
return false;
}
#endregion
#region 定義局部變量
long startBytes = 0;
int packSize = 1024 * 10; //分塊讀取,每塊10K bytes
string fileName = Path.GetFileName(filePath);
FileStream myFile = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
BinaryReader br = new BinaryReader(myFile);
long fileLength = myFile.Length;
int sleep = (int)Math.Ceiling(1000.0 * packSize / speed);//毫秒數:讀取下一數據塊的時間間隔
string lastUpdateTiemStr = File.GetLastWriteTimeUtc(filePath).ToString("r");
string eTag = HttpUtility.UrlEncode(fileName, Encoding.UTF8) + lastUpdateTiemStr;//便於恢復下載時提取請求頭;
#endregion
#region--驗證:文件是否太大,是否是續傳,且在上次被請求的日期之後是否被修
if (myFile.Length > Int32.MaxValue)
{//-------文件太大了-------
httpContext.Response.StatusCode = 413;//請求實體太大
return false;
}
if (httpContext.Request.Headers["If-Range"] != null)//對應響應頭ETag:文件名+文件最後修改時間
{
//----------上次被請求的日期之後被修改過--------------
if (httpContext.Request.Headers["If-Range"].Replace("\"", "") != eTag)
{//文件修改過
httpContext.Response.StatusCode = 412;//預處理失敗
return false;
}
}
#endregion
try
{
#region -------添加重要響應頭、解析請求頭、相關驗證-------------------
httpContext.Response.Clear();
httpContext.Response.Buffer = false;
httpContext.Response.AddHeader("Content-MD5", GetMD5Hash(myFile));//用於驗證文件
httpContext.Response.AddHeader("Accept-Ranges", "bytes");//重要:續傳必須
httpContext.Response.AppendHeader("ETag", "\"" + eTag + "\"");//重要:續傳必須
httpContext.Response.AppendHeader("Last-Modified", lastUpdateTiemStr);//把最後修改日期寫入響應
httpContext.Response.ContentType = "application/octet-stream";//MIME類型:匹配任意文件類型
httpContext.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8).Replace("+", "%20"));
httpContext.Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
httpContext.Response.AddHeader("Connection", "Keep-Alive");
httpContext.Response.ContentEncoding = Encoding.UTF8;
if (httpContext.Request.Headers["Range"] != null)
{//------如果是續傳請求,則獲取續傳的起始位置,即已經下載到客戶端的字節數------
httpContext.Response.StatusCode = 206;//重要:續傳必須,表示局部范圍響應。初始下載時默認為200
string[] range = httpContext.Request.Headers["Range"].Split(new char[] { '=', '-' });//"bytes=1474560-"
startBytes = Convert.ToInt64(range[1]);//已經下載的字節數,即本次下載的開始位置
if (startBytes < 0 || startBytes >= fileLength)
{//無效的起始位置
return false;
}
}
if (startBytes > 0)
{//------如果是續傳請求,告訴客戶端本次的開始字節數,總長度,以便客戶端將續傳數據追加到startBytes位置後----------
httpContext.Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
}
#endregion
#region -------向客戶端發送數據塊-------------------
br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
int maxCount = (int)Math.Ceiling((fileLength - startBytes + 0.0) / packSize);//分塊下載,剩余部分可分成的塊數
for (int i = 0; i < maxCount && httpContext.Response.IsClientConnected; i++)
{//客戶端中斷連接,則暫停
httpContext.Response.BinaryWrite(br.ReadBytes(packSize));
httpContext.Response.Flush();
if (sleep > 1) Thread.Sleep(sleep);
}
#endregion
}
catch
{
ret = false;
}
finally
{
br.Close();
myFile.Close();
}
}
catch
{
ret = false;
}
return ret;
}