用Generic Handler(ashx)去显示非二进制的图片

一般情况,显示非二进制的图片(存放在磁盘上的图片文件),直接用图片控件轻易实现。

< img  alt =""  src ="xxx.jpg"   />

< asp:Image  ID ="Image1"  runat ="server"  ImageUrl ="xxx.jpg"   />

 

由于程序要求,需要把图片文件转为数据流(二进制),再进行显示。因此想起使用Generic Handler(ashx)来处理。

你可以参考下面代码:

用Generic Handler(ashx)去显示非二进制的图片 View Code
<% @ WebHandler Language = " C# "  Class = " ViewImage "   %>

using  System;
using  System.Data;
using  System.Drawing;
using  System.IO;
using  System.Web;
using  System.Web.UI.WebControls;

public   class  ViewImage : IHttpHandler
{
    
public   void  ProcessRequest(HttpContext context)
    {
        
// 接收图片路径
         string  parameter  =  context.Request.QueryString[ " file " ];      
        
// 使用UrlDecode解编码  
         string  path  =  context.Server.MapPath(HttpUtility.UrlDecode(parameter));
        
// 转为字节
         byte [] datas  =  System.IO.File.ReadAllBytes(path);
        
// 输出数据流
        context.Response.OutputStream.Write(datas,  0 , datas.Length);
    }
 
    
public   bool  IsReusable
    {
        
get
        {
            
return   false ;
        }
    }
}

  

xxx.NavigateUrl  =   " ~/ViewImage.ashx?file= "   +  fileFullPath;

 

 

你可能感兴趣的:(handler)