转超难挑战:Response.Flush()与迅雷的矛盾
原文地址http://q.cnblogs.com/q/40757/
#region -------添加重要响应头、解析请求头、相关验证-------------------
httpContext.Response.Clear();
httpContext.Response.BufferOutput = false;//此处如果设为false,会导致迅雷打开并取消后一直阻塞asp.net进程
//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=" + ProcessFileName(Path.GetFileName(filePath)));
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));
//考虑取消下面一行,否则导致迅雷打开并取消后一直阻塞asp.net进程
httpContext.Response.Flush();
if (sleep > 1) System.Threading.Thread.Sleep(sleep);
}
#endregion

浙公网安备 33010602011771号