首页 > 編程·程序設計 > Asp.Net 2.0 防盗下载文件

Asp.Net 2.0 防盗下载文件

2008年5月25日 編程·程序設計 800 views
C#代码
  1. public void downLoad(string path)   
  2. {   
  3.     try  
  4.     {   
  5.         string filePath = path;   
  6.         int temp = filePath.LastIndexOf("/") + 1;   
  7.         string fileName = filePath.Substring(temp, filePath.Length - temp);   
  8.         //FileStream fileStream = new FileStream(Server.MapPath(filePath), FileMode.Open, FileAccess.Read, FileShare.Read);   
  9.   
  10.         FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);   
  11.   
  12.         long fileSize = fileStream.Length;   
  13.         Context.Response.ContentType = "application/octet-stream";   
  14.         Context.Response.AddHeader("Content-Disposition""attachment; filename="" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) + """);   
  15.         Context.Response.AddHeader("Content-Length", fileSize.ToString());   
  16.         byte[] fileBuffer = new byte[fileSize];   
  17.         fileStream.Read(fileBuffer, 0, (int)fileSize);   
  18.         fileStream.Close();   
  19.         Context.Response.BinaryWrite(fileBuffer);   
  20.         Context.Response.End();   
  21.     }   
  22.     catch  
  23.     {   
  24.         Response.Write("<script>alert(‘查无此资料或已被删除’);</script>");   
  25.     }   
  26. }  

作者:Johnny
原文链接:Asp.Net 2.0 防盗下载文件

声明: 本站遵循 署名-非商业性使用-相同方式共享 3.0 共享协议. 转载请注明转自 寂寞部屋

  1. 目前还没有任何评论.
  1. 目前还没有任何 trackbacks 和 pingbacks.