I used to mistakenly think that multi‑thread resumable upload could not be implemented through programming in ASP. NET. Today I finally got such a solution, which makes me understand that there are still many things to learn.
This solution is based on other solutions and related materials and improved according to my own understanding. if there are any errors or omissions, please note that, if there are other better solutions, please recommend them. Thank you for your consideration.
System. Io. Stream istream = Null ;
// Buffer to read 10 K bytes in Chunk:
Byte [] Buffer = New Byte [ 10240 ];
// Length of the file:
Int Length;
// Total Bytes to read:
Long Datatoread;
// Identify the file to download including its path.
String Filepath = @" E: \ Software \ SQL Server 2000 Personal Edition. ISO " ;
// Identify the file name.
String Filename = System. Io. Path. getfilename (filepath );
Try
{
// Open the file.
Istream = New System. Io. filestream (filepath, system. Io. filemode. Open,
System. Io. fileaccess. Read, system. Io. fileshare. Read );
Response. Clear ();
// Total Bytes to read:
Datatoread = Istream. length;
Long P = 0 ;
If (Request. headers [ " Range " ] ! = Null )
{
Response. statuscode = 206 ;
P = Long . Parse (request. headers [ " Range " ]. Replace ( " Bytes = " , "" ). Replace ( " - " , "" ));
}
If (P ! = 0 )
{
Response. addheader ( " Content-Range " , " Bytes " + P. tostring () + " - " + (( Long ) (Datatoread - 1 ). Tostring () + " / " + Datatoread. tostring ());
}
Response. addheader ( " Content-Length " ,(( Long ) (Datatoread - P). tostring ());
Response. contenttype = " Application/octet-stream " ;
Response. addheader ( " Content-Disposition " , " Attachment; filename = " + System. Web. httputility. urlencode (request. contentencoding. getbytes (filename )));
Istream. Position = P;
Datatoread = Datatoread - P;
// Read the bytes.
While (Datatoread > 0 )
{
// Verify that the client is connected.
If (Response. isclientconnected)
{
// Read the data in buffer.
Length = Istream. Read (buffer, 0 , 10240 );
// Write the data to the current output stream.
Response. outputstream. Write (buffer, 0 , Length );
// Flush the data to the HTML output.
Response. Flush ();
Buffer = New Byte [ 10240 ];
Datatoread = Datatoread - Length;
}
Else
{< br> // prevent infinite loop if user disconnects
datatoread = - 1 ;
}
}
}
Catch (Exception ex)
{
//Trap the error, if any.
Response. Write ("Error:" +Ex. Message );
}
Finally
{
If (Istream ! = Null )
{
//Close the file.
Istream. Close ();
}
Response. End ();
}
List of links to the materials referenced in this solution (I would like to express my gratitude to the author ):
Http://blog.csdn.net/playyuer/archive/2004/08/02/58430.aspx
Http://www.httpsniffer.com/http/1416.htm
Http://support.microsoft.com/default.aspx? SCID = KB; en-US; 812406 & Product = ASPnet
Update:
This solution has been updated based on the issue raised by playyuer, and the response. Clear (); method is called before the output.