// 輸出硬盤文件,提供下載
  // 輸入參數 _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();
中國最大的web開發資源網站及技術社區,新聞熱點
疑難解答
圖片精選