参考:http://blog.csdn.net/Teng_s2000/archive/2005/10/21/510857.aspx
http://www.cnblogs.com/bestcomy/archive/2004/08/10/31950.html
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
namespace lianxi
{
public class Download
{
public Download()
{
}
public static void DownloadFile(HttpResponse Response, HttpRequest Request, string filepath, int speed)
{
if (!File.Exists(filepath))
{
Response.StatusCode = 404; //http状态代码,具体请看http://hi.baidu.com/%C3%AB%CE%D1/blog/item/7066a154993750133b2935ab.html
return;
}
string name = Path.GetFileName(filepath); //获取文件名
int packSize = 10240;
byte[] buffer = new byte[packSize];
long fileLength;
long startByets = 0;
FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
BinaryReader br = new BinaryReader(fs);
fileLength = fs.Length;
int sleep = (int)Math.Ceiling(1000.0 * packSize / speed); //用于单线程控制下载速度
try
{
Response.Clear();
Response.ClearHeaders();
Response.Buffer = false;
if (Request.Headers["Range"] != null)
{
Response.StatusCode = 206; //这个续传是必备的
startByets = long.Parse(Request.Headers["Range"].Replace("bytes=", "").Replace("-", "")); //获取客户端已经下载的字节数
}
if (startByets != 0)
{
Response.AddHeader("Content-Range", string.Format("bytes {0}-{1}/{2}", startByets, fileLength - 1, fileLength)); //续传必备,表示客户端从哪个字节开始下载,到哪个字节结束下载,具体请看http://hi.baidu.com/%C3%AB%CE%D1/blog/item/a630dfd3c18dbbd3a8ec9afc.html中的“Content-Range”,注意“fileLength - 1”,这是有点像数组,用文件的长度-1就可以得到数组的最后字节了。
}
Response.AddHeader("Content-Length", fileLength.ToString()); //告诉客户端所要下载文件的长度
Response.AddHeader("Accept-Ranges", "bytes"); //续传必备
Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(name, System.Text.Encoding.UTF8));//用于支持英文文件名
Response.ContentType = "application/octet-stream"; //一般是这个,这个请看http://baike.baidu.com/view/160611.htm(MIME百科)
Response.ContentEncoding = System.Text.Encoding.UTF8;
fs.Seek(startByets, SeekOrigin.Begin);//设置文件流的起点位置
int maxCount = (int)Math.Ceiling((fileLength - startByets + 0.0) / packSize);
for (int i = 0; i < maxCount && Response.IsClientConnected; i++)
{
//int length = fs.Read(buffer, 0, packSize);
//Response.OutputStream.Write(buffer, 0, packSize);
Response.BinaryWrite(br.ReadBytes(packSize));
Response.Flush();
if (sleep > 0) System.Threading.Thread.Sleep(sleep);
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
fs.Close();
}
}
}
}
2
// 输出硬盘文件,提供下载
// 输入参数 _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("下载文件出错!");