复制代码 代码如下:
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;
}
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;
}
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
暂无评论...
更新日志
2024年11月29日
2024年11月29日
- 凤飞飞《我们的主题曲》飞跃制作[正版原抓WAV+CUE]
- 刘嘉亮《亮情歌2》[WAV+CUE][1G]
- 红馆40·谭咏麟《歌者恋歌浓情30年演唱会》3CD[低速原抓WAV+CUE][1.8G]
- 刘纬武《睡眠宝宝竖琴童谣 吉卜力工作室 白噪音安抚》[320K/MP3][193.25MB]
- 【轻音乐】曼托凡尼乐团《精选辑》2CD.1998[FLAC+CUE整轨]
- 邝美云《心中有爱》1989年香港DMIJP版1MTO东芝首版[WAV+CUE]
- 群星《情叹-发烧女声DSD》天籁女声发烧碟[WAV+CUE]
- 刘纬武《睡眠宝宝竖琴童谣 吉卜力工作室 白噪音安抚》[FLAC/分轨][748.03MB]
- 理想混蛋《Origin Sessions》[320K/MP3][37.47MB]
- 公馆青少年《我其实一点都不酷》[320K/MP3][78.78MB]
- 群星《情叹-发烧男声DSD》最值得珍藏的完美男声[WAV+CUE]
- 群星《国韵飘香·贵妃醉酒HQCD黑胶王》2CD[WAV]
- 卫兰《DAUGHTER》【低速原抓WAV+CUE】
- 公馆青少年《我其实一点都不酷》[FLAC/分轨][398.22MB]
- ZWEI《迟暮的花 (Explicit)》[320K/MP3][57.16MB]