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; 
        } 
    } 

    
} 


你可能感兴趣的:(.net,文件下载,handler,C#,HttpWebRequest)