HttpHandler案例

1.訪問者信息:html

先新建名爲 訪問者信息.ashx的文件數據庫

<%@ WebHandler Language="C#" Class="訪問者信息" %>

using System;
using System.Web;

public class 訪問者信息 : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "image/JPEG";
        using(System.Drawing.Bitmap bitmap=new System.Drawing.Bitmap(350,300))
        {
            using(System.Drawing.Graphics g=System.Drawing.Graphics.FromImage(bitmap))
            {
                g.DrawString("IP:"+context.Request.UserHostAddress,new System.Drawing.Font("宋體",30),System.Drawing.Brushes.Red,0,0);
                g.DrawString("操做系統:" + context.Request.Browser.Platform, new System.Drawing.Font("宋體", 30), System.Drawing.Brushes.Red, 0, 50);
                g.DrawString("瀏覽器版本:" + context.Request.Browser.Platform, new System.Drawing.Font("宋體", 30), System.Drawing.Brushes.Red, 0, 100);
            }
            bitmap.Save(context.Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg);
        }
        
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}


執行後結果爲c#

 

 

 

 

 2.HttpHandler實現文件下載瀏覽器

      若是HttpHandler 輸出的是html、txt、jpeg等類型的信息,那麼瀏覽器會直接顯示,若是但願彈出保存對話框,則須要添加 Header:string encodeFileName=HttpUtility.UrlEncode("XXX.txt");Response.AddHeader("Content-Disposition",string.Format("attachment;filename=\"{0}\"",encodeFileName));服務器

其中filename 後爲編碼後的文件名。filename段爲建議的保存文件名app

 

先新建名爲  Download.ashx文件編碼

<%@ WebHandler Language="C#" Class="Download" %>url

using System; using System.Web;spa

public class Download : IHttpHandler {         public void ProcessRequest (HttpContext context) {         context.Response.ContentType = "image/JPEG";         string filename=HttpUtility.UrlEncode("AAAA.jpg");//url編碼,防止亂碼         context.Response.AddHeader("Content-Disposition", "attachment;filename="+filename);         context.Response.WriteFile("AAAA.jpg");            }       public bool IsReusable {         get {             return false;         }     }操作系統

}


 

 

 

 

 

3.先解釋下動態輸出的用處:不用再把資源保存到磁盤上在輸出(不會有文件重名的問題,文件不生成在服務器端。)

 

 

3.HttpHandler實現NPOI的相關操做

如今簡單舉個例子,

用NPOI動態生成一個Excel表而後彈出對話框讓用戶下載,文件名是「用戶列表.xls」。

 

(一).先簡單建立一個名爲UserInfo的數據庫,再新建個T_Users的表,有UserName,Password兩個字段。而後填入一些數據

 

(二).分別建立名爲DownloadExcel.aspx和DownloadExcel.ashx 兩個文件。

再DownloadExcel.ashx中。代碼以下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NPOI.HSSF.UserModel;
using System.Data.SqlClient;
using System.Data;

namespace NPOI_EXCEL_
{
    /// <summary>
    /// DownloadExcel 的摘要說明
    /// </summary>
    public class DownloadExcel : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            /*
            context.Response.ContentType = "application/x-excel";
            context.Response.ContentType = "application/x-excel";
            string filename = HttpUtility.UrlEncode("動態數據.xls");//文件名進行url編碼,防止亂碼
            context.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.CreateSheet();
            HSSFRow row = sheet.CreateRow(0);
            HSSFCell cell1 = row.CreateCell(0);
            cell1.SetCellValue("hell0");
            row.CreateCell(1).SetCellValue(3.14);
            workbook.Write(context.Response.OutputStream);
             */
            context.Response.ContentType = "application/x-excel";
            context.Response.ContentType = "application/x-excel";
            string filename = HttpUtility.UrlEncode("用戶列表.xls");//文件名進行url編碼,防止亂碼
            context.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.CreateSheet();

            using (SqlConnection conn = new SqlConnection(@"Data Source=SGBCNQ6RQ6IMM9V;Initial Catalog=UserInfo;User ID=sa;Password=123456"))
            {
                conn.Open();
                using(IDbCommand cmd=conn.CreateCommand())
                {
                    cmd.CommandText = "select * from T_Users";
                    using(IDataReader reader=cmd.ExecuteReader())
                    {
                        int rownum = 0;
                        while (reader.Read())
                        {
                            string username=reader.GetString(reader.GetOrdinal("UserName"));
                            string password=reader.GetString(reader.GetOrdinal("Password"));
                            HSSFRow row = sheet.CreateRow(rownum);

                            row.CreateCell(0).SetCellValue(username);
                            row.CreateCell(1).SetCellValue(password);
                            rownum++;
                        }
                    }
                }    
            }
            workbook.Write(context.Response.OutputStream);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}


 

關於NPOI的DLL能夠上網找找,很容易找到。

 

而後再DownloadExcel.aspx中,代碼以下:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DownloadExcel.aspx.cs" Inherits="NPOI_EXCEL_.DownloadExcel1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     <a href="DownloadExcel.ashx">DownloadExcel</a>
    </div>
    </form>
</body>
</html>


 

 

 

執行的結果爲:

 

而後數據庫的數據就導入到了EXCEL中了

相關文章
相關標籤/搜索