Rolinson's Blog

ASP.NET , J2ME , WAP
(还有收藏网络上的技术文章,以便一急之用)

博客园 首页 新随笔 联系 订阅 管理
 1 // 输出硬盘文件,提供下载 支持大文件、续传、速度限制、资源占用小
 2   // 输入参数 _Request: Page.Request对象,  _Response: Page.Response对象, _fileName: 下载文件名, _fullPath: 带文件名下载路径, _speed 每秒允许下载的字节数
 3   // 返回是否成功
 4   public static bool ResponseFile(HttpRequest _Request,HttpResponse _Response,string _fileName,string _fullPath, long _speed)
 5   {
 6    try
 7    {
 8     FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
 9     BinaryReader br = new BinaryReader(myFile);
10     try
11     {
12      _Response.AddHeader("Accept-Ranges""bytes");
13      _Response.Buffer = false;
14      long fileLength = myFile.Length;
15      long startBytes = 0;
16      
17      int pack = 10240//10K bytes
18      //int sleep = 200;   //每秒5次   即5*10K bytes每秒
19      int sleep = (int)Math.Floor(1000 * pack / _speed) + 1;
20      if (_Request.Headers["Range"!= null)
21      {
22       _Response.StatusCode = 206;
23       string[] range = _Request.Headers["Range"].Split(new char[] {'=''-'});
24       startBytes = Convert.ToInt64(range[1]);
25      }
26      _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
27      if (startBytes != 0)
28      {
29       _Response.AddHeader("Content-Range"string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength-1, fileLength));
30      }
31      _Response.AddHeader("Connection""Keep-Alive");
32      _Response.ContentType = "application/octet-stream";
33      _Response.AddHeader("Content-Disposition","attachment;filename=" + HttpUtility.UrlEncode(_fileName,System.Text.Encoding.UTF8) );
34  
35      br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
36      int maxCount = (int) Math.Floor((fileLength - startBytes) / pack) + 1;
37      for (int i = 0; i < maxCount; i++)
38      {
39       if (_Response.IsClientConnected)
40       {
41        _Response.BinaryWrite(br.ReadBytes(pack));
42        Thread.Sleep(sleep);
43       }
44       else
45       {
46        i=maxCount; 
47       }
48      }
49     }
50     catch
51     {
52      return false;
53     }
54     finally
55     {
56      br.Close();
57      myFile.Close();
58     }
59    }
60    catch
61    {
62     return false;
63    }
64    return true;
65   }
66 
67 
68 //调用例
69 
70    Page.Response.Clear();
71       
72    bool success = ResponseFile(Page.Request, Page.Response, "filename"@"C:\download.date"1024000);
73    
74    if(!success)
75     Response.Write("下载文件出错!");
76 
77    Page.Response.End();
78 
79 
posted on 2007-03-27 08:50  ByNow  阅读(320)  评论(0编辑  收藏  举报