asp.net| function | speed | download
Output hard disk file, provide download
Input parameter _request:page.request object, _response:page.response object, _filename: Download filename, _fullpath: Download path with filename, _speed number of bytes allowed per second
Returns whether successful
public static bool Responsefile (HttpRequest _request,httpresponse _response,string _filename,string _fullPath, Long _ Speed
{
Try
{
FileStream myFile = new FileStream (_fullpath, FileMode.Open, FileAccess.Read, fileshare.readwrite);
BinaryReader br = new BinaryReader (myFile);
Try
{
_response.addheader ("accept-ranges", "bytes");
_response.buffer = false;
Long filelength = myfile.length;
Long startbytes = 0;
int pack = 10240; 10K bytes
int sleep = 200; 5 times per second, 5*10k bytes per second
int sleep = (int) Math.floor (1000 * 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);
int maxcount = (int) math.floor (filelength-startbytes)/pack) + 1;
for (int i = 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;
}
Call Example
Page.Response.Clear ();
BOOL success = Responsefile (Page.Request, Page.Response, "filename", @ "C:\download.date", 1024000);
if (!success)
Response.Write ("Error downloading file!") ");
Page.Response.End ();