C#绑定事件及下载文件

本文介绍了一种在ASP.NET中实现文件下载的方法,通过TransmitFile函数设置HTTP响应头,使用户能直接下载服务器上的文件。该方法适用于需提供文件下载功能的Web应用。

绑定事件

//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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值