File upload read progress bar and breakpoint download for. NET Web sites

Source: Internet
Author: User
Tags ranges

Progress read when the file is uploaded to the server
 Upfileresult result = new Upfileresult ();     try {//Pre-read the file into memory, while calculating the upload progress IServiceProvider Provider = (IServiceProvider) httpcontext.current;         Returns the portion of the HTTP request body that has been read. HttpWorkerRequest request = (HttpWorkerRequest) provider.     GetService (typeof (HttpWorkerRequest)); Gets the upload size long length = long. Parse (Request.     Getknownrequestheader (httpworkerrequest.headercontentlength));     Checkfilesize (length, info); int bytesread = 0;          Read data size int read;  The size of the currently read block int count = 8192;     chunking size byte[] buffer;     Save all uploaded data byte[] tempbuff = null; if (Request! = null) {Tempbuff = Request.     Getpreloadedentitybody ();         } if (Tempbuff! = null) {buffer = new byte[length];         Chunked size count = tempbuff.length;         Copy the uploaded data past buffer.blockcopy (tempbuff, 0, Buffer, Bytesread, Count);         Start recording uploaded size bytesread = Tempbuff.length; Calculates the percentage of the currently uploaded file longPercent = Bytesread * 100/LENGTH;         Setpercent (SessionId, percent);         int II = 0; Loop block reads until all data is read over while (request. IsClientConnected () &&!request.                    isentireentitybodyispreloaded () && bytesread < length) {//If the last chunk size is less than the tile size, then the block is re-chunked                 if (Bytesread + count > Length) {count = (int) (length-bytesread);             Tempbuff = new Byte[count]; }//chunked reads read = Request.             Readentitybody (Tempbuff, Count);             Copy the read data block Buffer.blockcopy (tempbuff, 0, Buffer, bytesread, read);             Record uploaded size Bytesread + = read;             ii++;                 if (ii 10 = = 0) {//calculates the percentage of the currently uploaded file percent = Bytesread * 100/LENGTH;             Setpercent (SessionId, percent); } if (read = = 0) {//If the file was previously read(360 validation in global.asax), where data is not available, you need to avoid entering the dead loop break; }} if (Request. IsClientConnected () &&!request. Isentireentitybodyispreloaded ()) {//Incoming data uploaded//bindingflags bindingflags = B Indingflags.instance |             BindingFlags.NonPublic; Type type = Request.             GetType (); while ((type! = NULL) && (type. FullName = "System.Web.Hosting.ISAPIWorkerRequest")) {type = type.             BaseType; } if (type! = NULL) {type. GetField ("_contentavaillength", BindingFlags). SetValue (request, buffer.                 Length); Type. GetField ("_contenttotallength", BindingFlags). SetValue (request, buffer.                 Length); Type. GetField ("_preloadedcontent", BindingFlags).                 SetValue (request, buffer); Type. GetField ("_preloadedcontentread", BindingFlags).             SetValue (Request, true);   }//Indicates that the upload has ended         }} httppostedfile Imgfile = _request.     Files[0];     string fileName = Imgfile.filename;     UploadFile (result, Imgfile, FileName, info, SessionId);     Setpercent (SessionId, 100); return result; } catch (Exception ex) {result.     IsOk = false; Result. ErrMsg = ex.     Message; return result; }
Breakpoint download for server file
<summary>///support Breakpoint Download//</summary>///<param name= "Request" ></param>///<param name= " Response "></param>///<param name=" FilePath "> The Physical Address of the file </param>private void down (HttpRequest Request, HttpResponse Response, String filePath) {/* Breakpoint download is not the same as normal mode: Add a Property range:bytes=100000-response header to the requested header information for the breakpoint download Adds an attribute content-range=bytes 100000-19999/20000 returns a status code of 206 (Partial Content) that represents the first 500 bytes: range:bytes=0-499 represents the Two x 500 bytes: range:bytes=500-999 represents the last 500 bytes: range:bytes=-500 represents the range after 500 bytes: range:bytes=500-First and last byte: range:bytes= 0-0,-1 specify several ranges simultaneously: range:bytes=500-600,601-999 *///Open file using (Stream FileStream = new FileStream (FilePath, Fi        Lemode.open, FileAccess.Read, FileShare.Read)) {//Get file size long fileSize = filestream.length;        String range = request.headers["range"];        Response.Clear ();        Response.AddHeader ("accept-ranges", "bytes"); Response.AddHeader ("Connection", "Keep-alIve ");        Response.Buffer = false; Packet size int pack = 10240;        10Kb int sleep = 0; if (this. Speed.hasvalue) {sleep = (int) math.floor (1000.0 * 10/this.        Speed.value);        } long begin = 0;        Long end = FileSize-1; if (!string. IsNullOrEmpty (range)) {//Gets the scope of the request, if there are multiple scopes, temporarily processing only the first, range:bytes=500-600,601-999 range = Range .            Replace ("bytes=", "" "); Range = range.            Split (', ') [0]; string[] Region = range.            Split ('-'); String startPoint = Region[0].            Trim (); String endPoint = Region[1].            Trim (); if (StartPoint = = "") {long.                TryParse (EndPoint, out end);                begin = Filesize-end;            end = FileSize-1; } else if (EndPoint = = "") {long.                TryParse (StartPoint, out begin);            end = FileSize-1;            } else {    Long.                TryParse (StartPoint, out begin); Long.            TryParse (EndPoint, out end);            } response.statuscode = 206; Response.AddHeader ("Content-range", String.        Format ("bytes {0}-{1}/{2}", Begin, End, fileSize));        }//Byte stream to return data Response.ContentType = "Application/octet-stream";        response.contentencoding = System.Text.Encoding.UTF8; Response.AddHeader ("Content-disposition", "attachment; Filename=\ "" + Httputility.urlencode (Request.ContentEncoding.GetBytes (this.        FileName) + "\" ");        Long size = End-begin + 1; Response.AddHeader ("Content-length", size.        ToString ());        Create a bit array byte[] buffer = new Byte[pack];    Filestream.position = begin; Set the current stream position//When the file size is greater than 0 is into the loop while (Size > 0) {//Determines whether the client is still connected to the server if (Response .                isclientconnected) {//Gets the total number of bytes in the buffer.      int length = filestream.read (buffer, 0, pack);          Write Data Response.OutputStream.Write (buffer, 0, length);                Sends the output of the buffer to the client Response.Flush ();                Buffer = new Byte[pack];                size = Size-length;                if (Sleep > 0) {thread.sleep (sleep);            }} else {//when the user disconnects and exits the loop size =-1; }        }    }}

File breakpoint upload, pending additions

File upload read progress bar and breakpoint download for. NET Web sites

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.