ASP. C # breakpoint Continuation download Accept-ranges

Source: Internet
Author: User

Transferred from: http://www.cnblogs.com/90nice/p/3489287.html

1. Because you want to download large files need to continue to pass the breakpoint, using multi-threaded multipart download efficiency is higher, save resources.

The point of complaining: Download can be multi-threaded, if it is uploaded I feel no need. If it is a normal user (ADSL) upload speed only 50kb/s as far as I know 100MB fiber home user Download theoretical value can reach 12.5mb/s but the upload now only 256kb/s this speed enough to dry what. Hope that the upload download speed will be consistent.

The following is a simple example:

Service side:

If it is a fragment download in the HTTP header header file to have a range, the following will be an example of the client.

varRange = request.headers["Range"]; if(NULL==range) { //Normal ConditionResponse.statuscode = $; Response.ContentType="application/x-zip-compressed"; Response.AddHeader ("content-disposition","attachment;filename="+fName); FileStream FS=NewFileStream (FURL, FileMode.Open);LongLen =FS. Length; Fs. Close (); Fs. Dispose (); Response.AddHeader ("accept-ranges", Len. ToString ()); Response.TransmitFile (FURL); } Else { //Accept-range Situationstring[] re = range. Split ('='); string[] r = re[1]. Split ('-'); LongStart =0; LongAlength =0; LongFslength =0; //if start is empty starting from 0 fetchif(string. IsNullOrEmpty (r[0]) Start=0; ElseStart= Convert.toint64 (r[0]); //Fetch Total file lengthFileStream fs =NewFileStream (FURL, FileMode.Open); Fslength=FS. Length; Fs. Close (); Fs. Dispose (); //byte lengthif(string. IsNullOrEmpty (r[1])) Alength= Fslength-start;ElseAlength= Convert.toint64 (r[1]) -start; Response.statuscode=206;//Multipart Download StatusResponse.ContentType ="application/x-zip-compressed"; Response.AddHeader ("content-disposition","attachment;filename="+fName); Response.AddHeader ("accept-ranges", (Alength-start). ToString ()); Response.AddHeader ("Content-range","bytes"+ Start +"-"+ (start + alength) +"/"+ Fslength. ToString ());//Content-range:bytes 100-200/1024 tells the client the file location and total file size for this request//How many bytes are taken from the file path start locationResponse.TransmitFile (FURL, start, alength);

Client Example:

Create an HTTP request and write to the requested file segment

varRequest = (HttpWebRequest) webrequest.create ("Http://localhost:40337/PublicPage/ZrqPublicImg.zip"); Request. AddRange (0, -); Try { //Get HTTP response, note HttpWebResponse inherits from IDisposable using(varResponse =(HttpWebResponse) request. GetResponse ()) {if(Response. StatusCode = =Httpstatuscode.ok)Throw NewException ("file does not support the range section download"); //setting buffers for receiving informationvarbytes =New byte[ the]; //gets the stream of the response (byte stream)using(varstream =Response. GetResponseStream ()) {//Filemode.append I'm writing from the end of the file. If it is multithreaded, write the file according to the location of the specific request.using(varOutStream =NewFileStream (@"D:\222.jpg", Filemode.append, FileAccess.Write, Fileshare.none)) { Const intBufferlen =4096; byte[] buffer =New byte[Bufferlen];intCount =0; while(count = stream. Read (Buffer,0, Bufferlen)) >0) {outstream.write (buffer,0, Count); } outstream.close (); Stream. Close (); } } } } Catch(Exception ex) {Console.WriteLine ("error message: {0}", ex. Message); }

Following excerpt from: http://www.sufeinet.com/forum.php?mod=viewthread&tid=2258&extra=page%3D1%26filter%3Dtypeid% 26typeid%3d284%26typeid%3d284

A method (server code) with support for speed limit download is also attached:

/// <summary>        ///output hard disk file, provide download support large file, resume, speed limit, small resource consumption/// </summary>        /// <param name= "_request" >; Page.Request Object</param>        /// <param name= "_response" >; Page.Response Object</param>        /// <param name= "_filename" >Download file name</param>        /// <param name= "_fullpath" >download path with file name</param>        /// <param name= "_speed" >number of bytes allowed to download per second</param>        /// <returns>returns whether successful</returns>        //---------------------------------------------------------------------        //Call://string Fullpath=server.mappath ("Count.txt"); //Responsefile (this. Request,this.        Response, "Count.txt", fullpath,100); //---------------------------------------------------------------------         Public Static BOOLResponsefile (HttpRequest _request, HttpResponse _response,string_filename,string_fullpath,Long_speed) {            Try{FileStream MyFile=NewFileStream (_fullpath, FileMode.Open, FileAccess.Read, fileshare.readwrite); BinaryReader BR=NewBinaryReader (MyFile); Try{_response.addheader ("accept-ranges","bytes"); _response.buffer=false; LongFilelength =myfile.length; LongStartbytes =0; intPack =10240;//10K bytes                    intSleep = (int) Math.floor (Double)( +* Pack/_speed) +1; if(_request.headers["Range"] !=NULL) {_response.statuscode=206; string[] range = _request.headers["Range"]. Split (New Char[] {'=','-' }); Startbytes= Convert.toint64 (range[1]); } _response.addheader ("Content-length", (Filelength-startbytes).                    ToString ()); if(Startbytes! =0) {_response.addheader ("Content-range",string. Format ("bytes {0}-{1}/{2}", Startbytes, Filelength-1, filelength)); } _response.addheader ("Connection","keep-alive"); _response.contenttype="Application/octet-stream"; _response.addheader ("content-disposition","attachment;filename="+Httputility.urlencode (_filename, System.Text.Encoding.UTF8)); Br.                    Basestream.seek (Startbytes, Seekorigin.begin); intMaxCount = (int) Math.floor (Double) ((filelength-startbytes)/pack) +1;  for(inti =0; i < MaxCount; i++)                    {                        if(_response.isclientconnected) {_response.binarywrite (br.                            Readbytes (pack));                        Thread.Sleep (Sleep); }                        Else{i=MaxCount; }                    }                }                Catch                {                    return false; }                finally{br.                    Close ();                Myfile.close (); }            }            Catch            {                return false; }            return true; }    }

ASP. C # breakpoint Continuation download Accept-ranges

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.