文件下载的后台代码

下载事件 
        //下载按钮事件
         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/p/2613080.html