IE的自带下载功能中没有断点续传功能,要实现断点续传功能,需要用到HTTP协议中鲜为人知的几个响应头和请求头。
一. 两个必要响应头Accept-Ranges、ETag
客户端每次提交下载请求时,服务端都要添加这两个响应头,以保证客户端和服务端将此下载识别为可以断点续传的下载:
Accept-Ranges:告知下载客户端这是一个可以恢复续传的下载,存放本次下载的开始字节位置、文件的字节大小;
ETag:保存文件的唯一标识(我在用的文件名+文件最后修改时间,以便续传请求时对文件进行验证);
Last-Modified:可选响应头,存放服务端文件的最后修改时间,用于验证
二. 一个重要请求头Range
Range:首次下载时,Range头为null,此时服务端的响应头中必须添加响应头Accept-Ranges、ETag;
续传请求时,其值表示客户端已经收到的字节数,即本次下载的开始字节位置,服务端依据这个 值从相应位置读取数据发送到客户端。
三. 用于验证的请求头If-Range、
当响应头中包含有Accept-Ranges、ETag时,续传请求时,将包含这些请求头:
If-Range:对应响应头ETag的值;
Unless-Modified-Since:对应响应头Last-Modified的值。
续传请求时,为了保证客户端与服务端的文件的一致性和正确性,有必要对文件进行验证,验证需要自己写验证代码,就根据解析这两个请求头的值,将客户端已下载的部分与服务端的文件进行对比,如果不吻合,则从头开始下载,如果吻合,则断点续传。
四. 速度限制
程序中加入了速度限制,用于对客户端进行权限控制的流量限制。
五. 其它注意事项
如:文件名乱码的问题、文件名中空格变加号、强制客户端显示下载对话框等,详见源码注释:
Java代码
class="star" src="/Upload/Images/2014062721/40B102E0EF997EA6.png" alt="收藏代码" />
- public static bool DownloadFile(HttpContext httpContext, string filePath, long speed)
- {
- bool ret = true;
- try
- {
- #region--验证:HttpMethod,请求的文件是否存在
- switch (httpContext.Request.HttpMethod.ToUpper())
- {
- 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;
- 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)
- {
-
- 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";
- 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;
- string[] range = httpContext.Request.Headers["Range"].Split(new char[] { '=', '-' });
- startBytes = Convert.ToInt64(range[1]);
- if (startBytes < 0 || startBytes >= fileLength)
- {
- return false;
- }
- }
- if (startBytes > 0)
- {
- 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;
- }
转自:http://www.cnblogs.com/gjahead/archive/2007/06/18/787654.html