C# Handler 下载文件

假设前台服务器和应用服务器分开,前台服务器有N台负责展现,应用服务器部署文件生成服务,应用服务器火墙策略未对所有用户开放,如果要实现前台下载应用服务器生成功能,一种方法可以通过同步服务将应用服务器生成的文件同步分发到各个前台服务器,另一种方法是前台服务器将下载链接请求统一转到一个Hander,由Handler负责向应用服务器请求文件流并返回到前台页面。

注意:应用服务器文件生成目录也发布一个网站,Handler向应用服务器发送请求:

 HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(result); 

<%@ WebHandler Language="C#" Class="DowdloadFileHandler" %> 

using System; 
using System.Web; 
using System.Data; 
using System.IO; 
using System.Net; 
using System.Text; 

public class DowdloadFileHandler : IHttpHandler 
{ 

    public void ProcessRequest(HttpContext context) 
    { 


        string industry_code = context.Request["industry_code"] == null ? "-1" : context.Request["industry_code"].ToString(); 
        string capital_code = context.Request["capital_code"] == null ? "-1" : context.Request["capital_code"].ToString(); 
        string str_date = context.Request["str_date"] == null ? DateTime.Now.ToString("yyyyMMdd") : context.Request["str_date"].ToString(); 


        CookieContainer cookie = new CookieContainer(); 
        string contentType = "application/x-www-form-urlencoded;"; 
        string accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/x-silverlight, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, application/x-silverlight-2-b1, */*"; 
        string userAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)"; 


        //string path = InitXMLDataPath(); 
        string path = System.Configuration.ConfigurationManager.AppSettings["RCXMLDataPath"].ToString(); 

        string result = path + industry_code + "_" + capital_code + "_" + str_date + ".xls"; 

        string fileName = industry_code + "_" + capital_code + "_" + str_date + ".xls"; 

        //string filePath = context.Server.MapPath(result); 
        //FileInfo fileInfo = new FileInfo(result); 
        //context.Response.Clear(); 
        //context.Response.ClearContent(); 
        //context.Response.ClearHeaders(); 
        //context.Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName); 
        //context.Response.AddHeader("Content-Length", fileInfo.Length.ToString()); 
        //context.Response.AddHeader("Content-Transfer-Encoding", "binary"); 
        //context.Response.ContentType = "application/octet-stream"; 
        //context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); 
        //context.Response.WriteFile(fileInfo.FullName); 
        //context.Response.Flush(); 
        //context.Response.End(); 

        //WebClient client = new WebClient(); 
        //Stream str = client.OpenRead(result); 
        //StreamReader reader = new StreamReader(str); 
        //context.Response.Clear(); 
        //context.Response.ClearContent(); 
        //context.Response.ClearHeaders(); 
        //context.Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName); 
        //context.Response.AddHeader("Content-Length", reader.ReadToEnd().Length.ToString()); 
        //context.Response.AddHeader("Content-Transfer-Encoding", "binary"); 
        //context.Response.ContentType = "application/octet-stream"; 
        //context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); 
        //context.Response.Flush(); 
        //context.Response.End(); 

        //string param = "hl=zh-cn&newwindow=1"; 
        //byte[] bs = Encoding.ASCII.GetBytes(param); 
        //req.Method = "Post"; 
        //req.ContentType = "application/x-www-form-urlencoded"; 
        //req.ContentLength = bs.Length; 

        //string temp_excel_file_name = context.Server.MapPath("RCXMLPath")  + fileName; 
        string temp_excel_file_name = System.Configuration.ConfigurationManager.AppSettings["RCExcelPath"].ToString() + fileName; 
                
        if (!File.Exists(temp_excel_file_name)) 
        { 
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(result); 

            req.UserAgent = userAgent; 
            req.ContentType = contentType; 
            req.CookieContainer = cookie; 
            req.Accept = accept; 
            req.Method = "GET"; 
            req.Timeout = 30 * 1000; 

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); 
            System.IO.Stream stream = resp.GetResponseStream(); 
            StreamReader reader = new StreamReader(stream); 

            byte[] buffer = new byte[32 * 1024]; 
            int bytesProcessed = 0; 

            System.IO.FileStream fs = System.IO.File.Create(temp_excel_file_name); 

            int bytesRead; 
            do 
            { 
                bytesRead = stream.Read(buffer, 0, buffer.Length); 
                fs.Write(buffer, 0, bytesRead); 
                bytesProcessed += bytesRead; 
            } 
            while (bytesRead > 0); 
            
            fs.Flush(); 
            fs.Close(); 
            resp.Close(); 
        } 
        string filePath = temp_excel_file_name; 
        FileInfo fileInfo = new FileInfo(filePath); 
        context.Response.Clear(); 
        context.Response.ClearContent(); 
        context.Response.ClearHeaders(); 
        context.Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName); 
        context.Response.AddHeader("Content-Length", fileInfo.Length.ToString()); 
        context.Response.AddHeader("Content-Transfer-Encoding", "binary"); 
        context.Response.ContentType = "application/octet-stream"; 
        context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); 
        context.Response.WriteFile(fileInfo.FullName); 
        context.Response.Flush(); 
        context.Response.End(); 



    } 

    public bool IsReusable 
    { 
        get 
        { 
            return false; 
        } 
    } 

    
} 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值