前端 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CSASPNETLimitDownloadSpeed.Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:DropDownList ID="ddlDonwloadSpeed" runat="server"> <asp:ListItem Value="20">20 Kb/s</asp:ListItem> <asp:ListItem Value="50">50 Kb/s</asp:ListItem> <asp:ListItem Value="80">80 Kb/s</asp:ListItem> </asp:DropDownList> <asp:Button ID="btnDownload" runat="server" Text="Download" OnClick="btnDownload_Click" /> </div> </form> </body> </html> 后端 [code=csharp]using System; using System.Web; using System.IO; using System.Threading;namespace CSASPNETLimitDownloadSpeed { public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // You can enlarge the size of the file to have a longer download period later. // 1024 * 1024 * 1 = 1 Mb int length = 1024 * 1024 * 1; byte[] buffer = new byte[length]; string filepath = Server.MapPath("~/bigFileSample.dat"); using (FileStream fs = new FileStream(filepath, FileMode.Create, FileAccess.Write)) { fs.Write(buffer, 0, length); } } protected void btnDownload_Click(object sender, EventArgs e) { string outputFileName = "bigFileSample.dat"; string filePath = Server.MapPath("~/bigFileSample.dat"); string value = ddlDonwloadSpeed.SelectedValue; // 1024 * 20 = 20 Kb/s. int downloadSpeed = 1024 * int.Parse(value); Response.Clear(); // Call DownloadFileWithLimitedSpeed method to download the file. try { DownloadFileWithLimitedSpeed(outputFileName, filePath, downloadSpeed); } catch (Exception ex) { Response.Write(@"<p><font color=""red"">"); Response.Write(ex.Message); Response.Write(@"</font></p>"); } Response.End(); } public void DownloadFileWithLimitedSpeed(string fileName, string filePath, long downloadSpeed) { if (!File.Exists(filePath)) { throw new Exception("Err: There is no such a file to download."); } // Get the BinaryReader instance to the file to download. using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { using (BinaryReader br = new BinaryReader(fs)) { Response.Buffer = false; // The file length. long fileLength = fs.Length; // The minimum size of a package 1024 = 1 Kb. int pack = 1024; // The original formula is: sleep = 1000 / (downloadspeed / pack) // which equals to 1000.0 * pack / downloadSpeed. // And here 1000.0 stands for 1000 millisecond = 1 second int sleep = (int)Math.Ceiling(1000.0 * pack / downloadSpeed); // Set the Header of the current Response. Response.AddHeader("Content-Length", fileLength.ToString()); Response.ContentType = "application/octet-stream"; string utf8EncodingFileName = HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8); Response.AddHeader("Content-Disposition", "attachment;filename=" + utf8EncodingFileName); // The maxCount stands for a total count that the thread sends the file pack. int maxCount = (int)Math.Ceiling(Convert.ToDouble(fileLength) / pack); for (int i = 0; i < maxCount; i++) { if (Response.IsClientConnected) { Response.BinaryWrite(br.ReadBytes(pack)); // Sleep the response thread after it sends a file pack. Thread.Sleep(sleep); } else { break; } } } } } } }[/code]
// 输入参数: // _Request: Page.Request对象 // _Response: Page.Response对象 // _fileName: 下载文件名 // _fullPath: 带文件名下载路径 // _speed 每秒允许下载的字节数 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次 即5*10K bytes每秒 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; } 调用示例:
Page.Response.Clear();
bool success = ResponseFile(Page.Request, Page.Response, "filename", @"C:\download.date", 1024000);
if(!success)
Response.Write("下载文件出错!");
Page.Response.End();
/// 输出硬盘文件,提供下载
/// </summary>
/// <param name="_fileName">下载文件名</param>
/// <param name="_fullPath">带文件名下载路径</param>
/// <param name="_speed">每秒允许下载的字节数</param>
/// <returns>返回是否成功</returns>
public static bool ResponseFile(string _fileName, string _fullPath, long _speed)
{
HttpRequest _Request = System.Web.HttpContext.Current.Request;
HttpResponse _Response = System.Web.HttpContext.Current.Response;
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次 即5*10K bytes每秒
int sleep = (int)Math.Floor((decimal)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.Charset = "UTF-8";
_Response.ContentEncoding = Encoding.UTF8;
_Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, Encoding.UTF8)); br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
int maxCount = (int)Math.Floor((decimal)(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;
}
}
_Response.End();
}
catch
{
return false;
}
finally
{
br.Close();
myFile.Close();
} }
catch (Exception err)
{
return false;
}
return true;
}
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CSASPNETLimitDownloadSpeed.Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="ddlDonwloadSpeed" runat="server">
<asp:ListItem Value="20">20 Kb/s</asp:ListItem>
<asp:ListItem Value="50">50 Kb/s</asp:ListItem>
<asp:ListItem Value="80">80 Kb/s</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="btnDownload" runat="server" Text="Download" OnClick="btnDownload_Click" />
</div>
</form>
</body>
</html>
后端
[code=csharp]using System;
using System.Web;
using System.IO;
using System.Threading;namespace CSASPNETLimitDownloadSpeed
{ public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// You can enlarge the size of the file to have a longer download period later.
// 1024 * 1024 * 1 = 1 Mb
int length = 1024 * 1024 * 1;
byte[] buffer = new byte[length]; string filepath = Server.MapPath("~/bigFileSample.dat");
using (FileStream fs = new FileStream(filepath, FileMode.Create, FileAccess.Write))
{
fs.Write(buffer, 0, length);
}
} protected void btnDownload_Click(object sender, EventArgs e)
{
string outputFileName = "bigFileSample.dat";
string filePath = Server.MapPath("~/bigFileSample.dat"); string value = ddlDonwloadSpeed.SelectedValue; // 1024 * 20 = 20 Kb/s.
int downloadSpeed = 1024 * int.Parse(value); Response.Clear(); // Call DownloadFileWithLimitedSpeed method to download the file.
try
{
DownloadFileWithLimitedSpeed(outputFileName, filePath, downloadSpeed);
}
catch (Exception ex)
{
Response.Write(@"<p><font color=""red"">");
Response.Write(ex.Message);
Response.Write(@"</font></p>");
}
Response.End();
} public void DownloadFileWithLimitedSpeed(string fileName, string filePath, long downloadSpeed)
{
if (!File.Exists(filePath))
{
throw new Exception("Err: There is no such a file to download.");
} // Get the BinaryReader instance to the file to download.
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (BinaryReader br = new BinaryReader(fs))
{ Response.Buffer = false; // The file length.
long fileLength = fs.Length; // The minimum size of a package 1024 = 1 Kb.
int pack = 1024; // The original formula is: sleep = 1000 / (downloadspeed / pack)
// which equals to 1000.0 * pack / downloadSpeed.
// And here 1000.0 stands for 1000 millisecond = 1 second
int sleep = (int)Math.Ceiling(1000.0 * pack / downloadSpeed);
// Set the Header of the current Response.
Response.AddHeader("Content-Length", fileLength.ToString());
Response.ContentType = "application/octet-stream"; string utf8EncodingFileName = HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8);
Response.AddHeader("Content-Disposition", "attachment;filename=" + utf8EncodingFileName); // The maxCount stands for a total count that the thread sends the file pack.
int maxCount = (int)Math.Ceiling(Convert.ToDouble(fileLength) / pack); for (int i = 0; i < maxCount; i++)
{
if (Response.IsClientConnected)
{
Response.BinaryWrite(br.ReadBytes(pack)); // Sleep the response thread after it sends a file pack.
Thread.Sleep(sleep);
}
else
{
break;
}
} }
}
}
}
}[/code]
很全的代码,非常感谢。
但这这个只能是下载flv ,没办法在线观看。求可以实现在线播放的解决办法