IE's own download function does not have a breakpoint to continue to transmit function, to achieve the function of breakpoint continuation, need to use the HTTP protocol in a few little-known response headers and request headers.
I. Two necessary responses head accept-ranges, ETag
Each time the client submits a download request, the server adds the two response headers to ensure that the client and the server recognize this download as a download that can be resumed by a breakpoint:
Accept-ranges: Tell the download client this is a resume download, storing the beginning byte location of the download, the size of the file bytes;
ETag: Save the unique identification of the file (I am using the filename + file last modified time, in order to renew the request to verify the file);
Last-modified: Optional response header that stores the last modification time of the server file to verify
Two. One important request header range
Range: When the first download, the range header is null, and the response header in the service side must add a accept-ranges, ETag;
When the request is renewed, the value indicates the number of bytes received by the client, that is, the start byte position of the download, which is sent to the client based on the value from which the server reads the data.
Three. Request headers for validation if-range,
When Accept-ranges, ETag are included in the response header, these request headers are included when the request is resumed:
If-range: Corresponds to the value of the response head ETag;
Unless-modified-since: The value corresponding to the response header last-modified.
In order to ensure the consistency and correctness of the client and server files when the request is renewed, it is necessary to verify the file, verify that you need to write their own verification code, based on the resolution of the two request headers, the client has downloaded part of the file with the server to compare, if it does not match, then download from the beginning, if the match, The breakpoint continues to pass.
Four. Speed limit
A speed limit is added to the program to restrict the traffic to the client for permission control.
Five. Other precautions
such as: file name garbled problem, file name hollow lattice variable Plus, mandatory client display Download dialog box, see Source code comments:
/**////<summary>///download files, support large files, continuous transmission, speed limits.
The response head accept-ranges, ETAG, and the request header range. Accept-ranges: Response header, indicating to the client that this process supports recoverable downloads. Implements the Background Intelligent Transfer Service (BITS) value: bytes///ETag: The response header, for the initial (200) response to the client, and recovery requests from the client,///
Each file must be provided with a unique ETag value (which can be composed of the file name and the date the file was last modified), which enables the client software to verify that the byte blocks that they have downloaded are still up to date.
Range: The starting position of the continuation, that is, the number of bytes already downloaded to the client, values such as: bytes=1474560-. In addition: UrlEncode encoding will be the file name in the space conversion + (+ conversion to%2b), but the browser can not understand the plus space, so in the browser to download the file, the space becomes a plus;///solution: After UrlEncode, will "+" replace "%" 20 "Because the browser converts%20 to spaces///</summary>///<param name=" HttpContext "> Current request httpcontext</param>///< param name= "FilePath" > Download the physical path to the file, including the path, filename </param>///<param name= "Speed" > Download speed: The number of bytes per second allowed to download </param >///<returns>true Download succeeded, false download failed </returns> public static bool DownloadFile (HttpContext HttpContext,
String FilePath, long speed {BOOL ret = true; try {#region--verify: HttpMethod, the requested file exists switch (HttpContext.Request.HttpMethod.ToUpper ()) {//currently supports only get and head method case "GE"
T ": Case ' head ': break; DeFault:httpContext.Response.StatusCode = 501;
return false; } if (!
File.exists (FilePath)) {httpContext.Response.StatusCode = 404;
return false;
#endregion #region defines a local variable long startbytes = 0; int packsize = 1024 * 10;
Chunk reads, each 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);/MS: Time interval for reading the next block of data string lastupdatetiemstr = File.getlastwritet IMEUTC (FilePath).
ToString ("R");
String eTag = Httputility.urlencode (FileName, Encoding.UTF8) + lastupdatetiemstr;//Extract request headers for easy recovery of downloads; #endregion #region--Verify that the file is too large, is a continuation, and that the IF (Myfile.length > Int32.MaxValue) {//-------file is too large after the last requested date-------HT
TpContext.Response.StatusCode = 413;//Request entity too large return false; } if (httpcontext.request.headers["If-range"]!= null)//corresponding response header etag: filename + file Last modified time {
--------------if (httpcontext.request.headers["If-range") was modified after----------last date requested.
Replace ("\", "")!= ETag) {//file Modified HttpContext.Response.StatusCode = 412;//preprocessing failed return false;
} #endregion try {#region-------Add an important response header, parse the request header, related validation-------------------httpContext.Response.Clear ();
HttpContext.Response.Buffer = false; HttpContext.Response.AddHeader ("Content-md5", Getmd5hash (MyFile));//For validating file HttpContext.Response.AddHeader (" Accept-ranges "," bytes ");/important: The continuation must be HttpContext.Response.AppendHeader (" ETag "," \ "" + ETag + "" ");/important: Renewal must be HttpContext . Response.appendheader ("last-modified", LASTUPDATETIEMSTR)//write the last modified date to the response HttpContext.Response.ContentType = " Application/octet-stream ";//mime type: matching arbitrary file type 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) {//------if it is a continuation request, get the starting position of the continuation, that is, the number of bytes that have been downloaded to the client------ HttpContext.Response.StatusCode = 206;//Important: The continuation must indicate a local range response. The default is string[] Range = httpcontext.request.headers["range" on initial download. Split (new char[] {' = ', '-'});//"bytes=1474560-" startbytes = Convert.toint64 (range[1));//The number of bytes already downloaded, that is, the starting position of this download if (start Bytes < 0 | |
Startbytes >= filelength) {//Invalid start position return false; } if (Startbytes > 0) {//------if it is a renewal request, tell the client the start byte number, the total length, so that the client appends the data to the startbytes position----------Httpcontext.respon Se. AddHeader ("Content-range", String.
Format ("bytes {0}-{1}/{2}", Startbytes, FileLength-1, filelength)); #endregion #region-------Send a block of data to the client-------------------Br.
Basestream.seek (Startbytes, Seekorigin.begin); int maxcount = (int) math.ceiling ((filelength-startbytes + 0.0)/packsize)//block download, the number of blocks to be divided for (int i = 0; i < max Count && HttpContext.Response.IsClientconnected; i++) {//client disconnects, suspend 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; }