博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

通过文件路径下载文件

Posted on 2008-06-16 15:18  LonelyStar  阅读(481)  评论(0)    收藏  举报

 

 1public partial class DownLoadFile : System.Web.UI.Page
 2    {
 3
 4        private string fileName = string.Empty;
 5
 6        protected void Page_Load(object sender, EventArgs e)
 7        {
 8            if (!IsPostBack)
 9            {
10                if (Request.QueryString["FileName"!= null)
11                {
12                    fileName = HttpUtility.UrlDecode(Request.QueryString["FileName"].ToString());
13                    DownLoad(fileName);
14                }

15            }

16        }

17
18
19
20        /// <summary>
21        /// Download file
22        /// </summary>
23        /// <param name="filePath">The file path.</param>

24        private void DownLoad(string filePath)
25        {
26            Response.Clear();
27            string fileName = Path.GetFileName(filePath);
28
29            FileStream fs = new FileStream(filePath, FileMode.Open);
30            byte[] bytes = new byte[(int)fs.Length];
31            fs.Read(bytes, 0, bytes.Length);
32            fs.Close();
33            Response.ContentType = "application/octet-stream";
34            //通知浏览器下载文件而不是打开 
35            Response.AddHeader("Content-Disposition""attachment; filename=" + HttpUtility.UrlDecode(fileName, System.Text.Encoding.UTF8));
36            Response.BinaryWrite(bytes);
37            Response.Flush();
38            Response.End();
39        }

40    }