C#绑定事件及下载文件

绑定事件

//Page_Load事件 
        protected void Page_Load(object sender, EventArgs e)
        {
         this.btnDownload.Click += new EventHandler(btnDownload_click);
        }
        
        //下载模板
        protected void btnDownload_click(object sender, EventArgs e)
        {
            TransmitFile("/uploads/Salary/SalaryTable.xlsx");
        }        
 1         /// <summary>
 2         /// 使用微软的TransmitFile下载文件
 3         /// </summary>
 4         /// <param name="filePath">服务器相对路径</param>
 5         public void TransmitFile(string filePath)
 6         {
 7             try
 8             {
 9                 filePath = Server.MapPath(filePath);
10                 if (File.Exists(filePath))
11                 {
12                     FileInfo info = new FileInfo(filePath);
13                     long fileSize = info.Length;
14                     HttpContext.Current.Response.Clear();
15 
16                     //指定Http Mime格式为压缩包
17                     HttpContext.Current.Response.ContentType = "application/x-zip-compressed";
18 
19                     // Http 协议中有专门的指令来告知浏览器, 本次响应的是一个需要下载的文件. 格式如下:
20                     // Content-Disposition: attachment;filename=filename.txt
21                     HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(info.FullName));
22                     //不指明Content-Length用Flush的话不会显示下载进度   
23                     HttpContext.Current.Response.AddHeader("Content-Length", fileSize.ToString());
24                     HttpContext.Current.Response.TransmitFile(filePath, 0, fileSize);
25                     HttpContext.Current.Response.Flush();
26                 }
27             }
28             catch
29             { }
30             finally
31             {
32                 HttpContext.Current.Response.Close();
33             }
34 
35         }

某博客:http://www.cnblogs.com/wang7/archive/2012/08/07/2627298.html

原文地址:https://www.cnblogs.com/Cein/p/7071252.html