国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > .NET > 正文

asp.net 文件下載實現代碼

2020-01-18 00:54:16
字體:
來源:轉載
供稿:網友
復制代碼 代碼如下:

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;
}
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 郓城县| 陈巴尔虎旗| 电白县| 陇西县| 长宁区| 灵璧县| 乐山市| 安西县| 海兴县| 舒兰市| 凌云县| 交城县| 阜宁县| 宁都县| 兴城市| 遂昌县| 庆元县| 廉江市| 翼城县| 平昌县| 家居| 内黄县| 曲阳县| 霍邱县| 鄄城县| 青田县| 铁岭县| 日喀则市| 达拉特旗| 滦平县| 绵阳市| 云霄县| 会昌县| 新乐市| 凤庆县| 乌拉特前旗| 大足县| 剑川县| 洛隆县| 洛隆县| 江永县|