使用.ashx动态显示图片

利用.ashx文件是一个更好的方法,这个文件类似于.aspx文件,可以通过它来调用HttpHandler类,从而免去了普通.aspx页面的控件解析以及页面处理的过程。这个文件特别适合于生成动态图片,生成动态文本等内容。

ShowPhoto.ashx里面就下面一句话

<% @ WebHandler language="C#" class="AspNetResources.Owc.ChartHandler" codebehind="ShowPhoto.cs" %>

其实也可以用这个代替

在web.config里面的<system.web>里面加上

 <httpHandlers>
  <add verb="*" path="*.ashx" type="AspNetResources.Owc, ChartHandler " validate="false" /> /*ChartHandler  是那个ashx.cs编译后生成的代码Assembly*/
   
  <!--Since we are grabbing all requests after this, make sure Error.aspx does not rely on .Text -->
  <add verb="*" path="Error.aspx" type="System.Web.UI.PageHandlerFactory" /> 
   

 </httpHandlers>

<%@ WebHandler Language="C#" Class="ShowPhoto" %>
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web;
using System.Configuration;
using System.Data.SqlClient;

public class ShowPhoto : IHttpHandler
{
   
    public bool IsReusable
    {
        get
        {
            return true;
        }
    }

    public void ProcessRequest(HttpContext context)
    {
        // Set up the response settings
        context.Response.ContentType = "image/jpg";
        context.Response.Cache.SetCacheability(HttpCacheability.Public);
        context.Response.BufferOutput = false;

        int photoId = -1;
        Stream stream = null;

        if (context.Request.QueryString["PhotoID"] != null && context.Request.QueryString["PhotoID"] != "")
        {
            photoId = Convert.ToInt32(context.Request.QueryString["PhotoID"]);
            stream = GetPhoto(photoId);
        }

        const int buffersize = 1024 * 16;
        byte[] buffer = new byte[buffersize];
        int count = stream.Read(buffer, 0, buffersize);
        while (count > 0)
        {
            context.Response.OutputStream.Write(buffer, 0, count);
            count = stream.Read(buffer, 0, buffersize);
        }
    }

    public Stream GetPhoto(int photoId)
    {
        string sqlPhoto = "select photo from account where userid=" + photoId;
        SqlDataReader result =DFBDSql.GetReader(sqlPhoto);
        result.Read();
        return new MemoryStream((byte[])result["photo"]);
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值