杂学日志

.net实现下载功能

ASP.NET中文件的下载(摘自http://www.aspxboy.com/private/showthread.asp?threadid=233
一.  服务端通过Response输出相应的HTTP  Response  Headers信息,和要下载的文件的数据来把文件发送到客户端,HTTP  Response  Headers表现在html文件中是下面的形式:
<meta  http-equiv="Content-Type"  content="text/htm  ">
http-equiv表示是Headers的名称,content表示这个Headers的值

二.  首先,要输出文件的MIME类型:
Page.Response.AddHeader(  "Content-Type",  “MIME类型”  );

三.  其次,要输出下载的文件的打开位置和文件名:
Page.Response.AddHeader("Content-Disposition",  "attachment;filename="  +  FileName  );
content -disposition  的  HTTP  response  header  允许指定文档表示的信息。使用这种  header  ,你就可以将文档指定成单独打开(而不是在浏览器中打开),还可以根据用户的操作来显示。如果用户要保存文档,你还可以为该文档建议一个文件名。这个建议名称会出现在  Save  As  对话框的“文件名”栏中。
attachment  ――  表示作为附件发送到客户端,客户端将单独打开此文件。
inline  ――  表示将在浏览器中打开这个文件。
filename  ――  表示发送到客户端文件的文件名。

四.  准备发送到客户端的文件数据:
不管什么类型的文件都要先转成byte类型的数组,然后将这个byte数组用Response.BinaryWrite方法输出到客户端。

      

string  path  ="G:\\download\\down.txt";
      System.IO.FileInfo  file  
=  new  System.IO.FileInfo(path);  
      Response.Clear();  
      Response.AddHeader(
"Content-Disposition",  "attachment;  filename="  +  HttpUtility.UrlEncode(file.Name));  

      Response.AddHeader(
"Content-Length",  file.Length.ToString());  
      Response.ContentType  
=  "application/octet-stream";  
      Response.WriteFile(file.FullName);  
      Response.End(); 

对于中文名解决方法:
string    filename    =  System.Web.HttpUtility.UrlEncode(  System.Text.Encoding.UTF8.GetBytes(filepath));
其他方式:
1,

private     void     FileDownload(string     fName,     string     path)  
  
{  
                  
long     lngFileSize;      
                  
byte[]     bytBuffer;      
                  
int     iReading;      
                  
string     sFileName     =     Server.MapPath(path     +     fName);      
                  Stream     outStream     
=     Response.OutputStream;      
                  Response.ContentType
="application/octet-stream";      
                  Response.AppendHeader(
"Connection","keep-alive");      
                  Response.AppendHeader(
"Content-Disposition","     attachment;     filename     =     "+fName     );      
                  FileStream     fStream     
=     new     FileStream(sFileName,FileMode.OpenOrCreate,FileAccess.Read);      
                  lngFileSize     
=     fStream.Length;      
                  bytBuffer     
=     new     byte[(int)lngFileSize];      
              
while((iReading=fStream.Read(bytBuffer,0,(int)lngFileSize))     >     0)      
              
{      
                  outStream.Write(bytBuffer,
0,iReading);      
              }
      
              fStream.Close();      
              outStream.Close();      
  }

2,

///   <summary>  
  
///   文件下载  
  
///   </summary>  
  
///   <param   name="FullFileName">包括路径在内的文件名</param>  

  public   static   void   FileDownloadByFullName(string   FullFileName)  
  
{  
  FileInfo   DownloadFile   
=   new   FileInfo(FullFileName);    
  HttpContext.Current.Response.Clear();  
  HttpContext.Current.Response.ClearHeaders();  
  HttpContext.Current.Response.Buffer
=false;  
  HttpContext.Current.Response.ContentType
="application/octet-stream";  
  HttpContext.Current.Response.AppendHeader(
"Content-Disposition","attachment;filename="   +HttpUtility.UrlEncode(DownloadFile.FullName,System.Text.Encoding.ASCII));  
  HttpContext.Current.Response.AppendHeader(
"Content-Length",DownloadFile.Length.ToString());  
  HttpContext.Current.Response.WriteFile(DownloadFile.FullName);  
  HttpContext.Current.Response.Flush();  
  HttpContext.Current.Response.End();  
  }

3, 
ASP.NET提供文件下载函数(支持大文件、续传、速度限制、资源占用小)    
   
  原稿CSDN网友   maling(***)   (   )    
   
  
//   输出硬盘文件,提供下载  
  
//   输入参数   _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();  

posted on 2006-12-25 12:04  一辉  阅读(2577)  评论(2编辑  收藏  举报

导航