文件下载的后台代码

下载事件 
        //下载按钮事件
         protected void lkb_downLoad_Click(object sender, EventArgs e)
         {
             //获取在隐藏控件的物理路径
             string fullPath = hf_upPath.Value;
 
             //获取包含在路径中的文件名
             string fileName = fullPath.Substring(fullPath.LastIndexOf('\\')+1);
 
             string extension = System.IO.Path.GetExtension(fullPath);
 
             //文件操作 
             FileInfo file = new FileInfo(fullPath);
 
             //清空缓存区的内容和HTTP头
             Response.Clear();
             Response.ClearContent();
             Response.ClearHeaders();
 
             //添加HTTP头
             Response.AddHeader("Content-Disposition", "attachment;filename=" +fileName);
             Response.AddHeader("Content-Length", file.Length.ToString());
             Response.AddHeader("Content-Transfer-Encoding", "binary");
 
             //由于有多种类型文件 判断选择对应的ContentType 
             switch (extension)
             {
                 case ".docx":
                 case ".doc":
                     Response.ContentType = "application/msword";
                     break;
                 case ".jpg":
                 case ".jpeg":
                     Response.ContentType = "image/jpeg";
                     break;
                 case ".gif":
                     Response.ContentType = "image/gif";
                     break;
                 case ".txt":
                     Response.ContentType = "text/plain";
                     break;
                 case ".bmp":
                     Response.ContentType = "application/x-bmp";
                     break;
                 default:
                     Response.ContentType = "application/octet-stream";
                     break;
             }
 
             //设置响应输出content的内容的编码
             Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
 
             //将文件写到输出流
             Response.WriteFile(file.FullName);
 
             //向客户端发送当前缓冲区的输出(内容必须大于256字节)
             Response.Flush();
 
             //使Web服务器停止处理脚本并返回当前结果
             Response.End();
         }

 

转载于:https://www.cnblogs.com/lcuzhanglei/archive/2012/07/28/2613080.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值