Support for breakpoint continuation in ASP. Download large file (ZT)

Source: Internet
Author: User
Tags ranges urlencode

IE's own download function does not have the ability to continue the breakpoint, in order to achieve the continuation of the breakpoint, you need to use the HTTP protocol, a few little-known response headers and request headers.
I. Two required response heads Accept-ranges, ETag
Each time a client submits a download request, both response headers are added to the server to ensure that the client and server recognize this download as a download that can be resumed on a breakpoint:
Accept-ranges: Tell the download client this is a download that can resume, storing the start byte location of this download, the size of the file bytes;
ETAG: The unique identification of the saved file (the file name I used and the last modification time of the files to verify the file when the request was continued);
Last-modified: Optional response header to store the last modified time of the server file for verification


Two. One important request header range
Range: When first downloaded, the range header is null, and the response header accept-ranges, ETag must be added to the server's response header;
When a request is continued, its value indicates the number of bytes that the client has received, that is, the start byte position of the download, and the server reads the data from the corresponding location to the client based on this value.

Three. Request headers for authentication if-range,
When a accept-ranges, ETag is included in the response header, the request headers are included when the request is resumed:
If-range: The value corresponding to the etag of the response head;
Unless-modified-since: The value corresponding to the response header last-modified.
The continuation of the request, in order to ensure that the client and server file consistency and correctness, it is necessary to verify the file, verify the need to write their own verification code, based on the resolution of the two request header values, the client has downloaded the portion of the server and the file to compare, if not match, then from the beginning to download, if it matches, Then the breakpoint continues to pass.

Four. Speed limit
A speed limit is added to the program, which limits the traffic to the client for permission control.

Five. Other precautions
such as: file name garbled problem, file name hollow lattice variable Plus, force client Display Download dialog box, see Source Comments:

Java code
  1. /**////<summary>
  2. Download files, support large files, continuous transmission, speed limit. The response head accept-ranges, ETAG, and request header range are continuously transmitted.
  3. Accept-ranges: The response header, which indicates to the client that this process supports recoverable downloads. Implement Background Intelligent Transfer Service (BITS) with a value of: bytes;
  4. ETag: The response header, the initial (200) response to the client, and the recovery request from the client,
  5. Each file must be provided with a unique ETag value (which can consist of the file name and the date the file was last modified), which enables the client software to verify that the block of bytes they have downloaded is still up to date.
  6. Range: The starting position of the continuation, that is, the number of bytes downloaded to the client, such as: bytes=1474560-.
  7. In addition: UrlEncode encoding will be the file name in the space conversion + (+ conversion to%2b), but the browser is not able to understand the plus is a space, so in the browser to download the file, the space becomes a plus;
  8. Workaround: After UrlEncode, replace "+" with "%20" because the browser converts%20 to a space
  9. </summary>
  10. <param name= "HttpContext" > Current request httpcontext</param>
  11. <param name= "FilePath" > The physical path of the downloaded file, including the path, file name </param>
  12. <param name= "Speed" > Download rate: bytes per second allowed to download </param>
  13. <returns>true download succeeded, false download failed </returns>
  14. Public static BOOL DownloadFile (HttpContext HttpContext, String FilePath, long speed)
  15. {
  16. BOOL ret = true;
  17. Try
  18. {
  19. #region--Verify: HttpMethod, the requested file exists
  20. switch (HttpContext.Request.HttpMethod.ToUpper ())
  21. { //currently only the get and head methods are supported
  22. case "GET":
  23. case "HEAD":
  24. Break ;
  25. Default:
  26. HttpContext.Response.StatusCode = 501;
  27. return false;
  28. }
  29. if (! File.exists (FilePath))
  30. {
  31. HttpContext.Response.StatusCode = 404;
  32. return false;
  33. }
  34. #endregion
  35. #region Defining Local Variables
  36. long startbytes = 0;
  37. int packsize = 1024x768 * 10; //block read, 10K bytes per block
  38. String fileName = Path.getfilename (FilePath);
  39. FileStream myFile = new FileStream (FilePath, FileMode.Open, FileAccess.Read, fileshare.readwrite);
  40. BinaryReader br = new BinaryReader (MyFile);
  41. long filelength = myfile.length;
  42. int sleep = (int) math.ceiling (1000.0 * packsize/speed); Number of milliseconds: the time interval to read the next block of data
  43. String lastupdatetiemstr = FILE.GETLASTWRITETIMEUTC (FilePath).  ToString ("R");
  44. String eTag = Httputility.urlencode (FileName, Encoding.UTF8) + lastupdatetiemstr;  //Easy to retrieve the request header when downloading;
  45. #endregion
  46. #region-Verify: Whether the file is too large, whether it is a continuation, and whether it was repaired after the last requested date
  47. if (Myfile.length > Int32.MaxValue)
  48. {//-------file is too large-------
  49. HttpContext.Response.StatusCode = 413; Request entity too large
  50. return false;
  51. }
  52. if (httpcontext.request.headers["If-range"]! = null)//corresponding response header etag: filename + file Last modified time
  53. {
  54. //----------has been modified since the last requested date--------------
  55. if (httpcontext.request.headers["If-range"]. Replace ("\" ", " ")! = ETag)
  56. {//file modified
  57. HttpContext.Response.StatusCode = 412; Preprocessing failed
  58. return false;
  59. }
  60. }
  61. #endregion
  62. Try
  63. {
  64. #region-------Add Critical response headers, parse request headers, and related validations-------------------
  65. HttpContext.Response.Clear ();
  66. HttpContext.Response.Buffer = false;
  67. HttpContext.Response.AddHeader ("Content-md5", Getmd5hash (MyFile)); Used to validate files
  68. HttpContext.Response.AddHeader ("Accept-ranges", "bytes"); IMPORTANT: Continued transmission must be
  69. HttpContext.Response.AppendHeader ("ETag", "\" "+ ETag + " \ "); IMPORTANT: Continued transmission must be
  70. HttpContext.Response.AppendHeader ("last-modified", lastupdatetiemstr); Write the last modified date to the response
  71. HttpContext.Response.ContentType = "Application/octet-stream"; MIME type: Matches any file type
  72. HttpContext.Response.AddHeader ("content-disposition", "attachment;filename=" + httputility.urlencode ( FileName, Encoding.UTF8).  Replace ("+", "%20"));
  73. HttpContext.Response.AddHeader ("Content-length", (filelength-startbytes).  ToString ());
  74. HttpContext.Response.AddHeader ("Connection", "keep-alive");
  75. httpContext.Response.ContentEncoding = Encoding.UTF8;
  76. if (httpcontext.request.headers["Range"]! = null)
  77. {//------If it is a continuation request, gets the starting position of the continuation, that is, the number of bytes that have been downloaded to the client------
  78. HttpContext.Response.StatusCode = 206; Important: The continuation must indicate a local range response. Initial download defaults to
  79. string[] Range = httpcontext.request.headers["range"]. Split (new char[] { ' = ', '-'}); "bytes=1474560-"
  80. Startbytes = Convert.toint64 (range[1]); The number of bytes that have been downloaded, that is, where the download started
  81. if (Startbytes < 0 | | startbytes >= filelength)
  82. {//invalid start position
  83. return false;
  84. }
  85. }
  86. if (Startbytes > 0)
  87. {//------If it is a continuation request, it tells the client the starting byte number, the total length, so that the client appends the continuation data to the Startbytes location----------
  88. HttpContext.Response.AddHeader ("Content-range", String.  Format ("bytes {0}-{1}/{2}", Startbytes, Filelength- 1, filelength));
  89. }
  90. #endregion
  91. #region-------Send a block of data to the client-------------------
  92. Br. Basestream.seek (Startbytes, Seekorigin.begin);
  93. int maxCount = (int) math.ceiling ((filelength-startbytes + 0.0)/packsize); Block download, the number of blocks that the remainder can be divided into
  94. For (int i = 0; i < maxCount && httpContext.Response.IsClientConnected; i++)
  95. {//client interrupts connection, pause
  96. HttpContext.Response.BinaryWrite (Br. Readbytes (packsize));
  97. HttpContext.Response.Flush ();
  98. if (Sleep > 1) thread.sleep (sleep);
  99. }
  100. #endregion
  101. }
  102. Catch
  103. {
  104. ret = false;
  105. }
  106. finally
  107. {
  108. Br. Close ();
  109. Myfile.close ();
  110. }
  111. }
  112. Catch
  113. {
  114. ret = false;
  115. }
  116. return ret;
  117. }



Transferred from: http://www.cnblogs.com/gjahead/archive/2007/06/18/787654.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.