Favorites: ASP. NET provides the file download function (supports large files, resume, speed limit, and small resource usage) (from: arhrun)
// Output the hard disk file for download
// Input parameter _ Request: page. request object, _ response: page. response object, _ filename: Download file name, _ fullpath: Download path with file name, _ speed bytes allowed to be downloaded per second
// Whether the response is 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;
// 10 K bytes
// Int sleep = 200;
// 5 times per second, that is, 5*10 K 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 ("An error occurred while downloading the file! ");
Page. response. End ();
In this way, the downloading is controllable, and the size of the file block to be read can be controlled. This effectively prevents theft and monitors the downloading of resources. If you can encapsulate it well, it will be a very powerful class.