1)右键网站新建,选择 generic handler,就是扩展名为ashx的那个.
2)
<%@ WebHandler Language="C#" class="ImageFetch" %>
using System;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.IO;
public class ImageFetch : IHttpHandler
{
const int BUFFERSIZE = 1024;
public bool IsReusable
{
get
{
return true;
}
}
public void ProcessRequest(HttpContext context)
{
HttpResponse response = context.Response;
HttpRequest request = context.Request;
response.ContentType = "image/jpeg";
response.Cache.SetCacheability(HttpCacheability.Public);
response.BufferOutput = false;
//这里取出你存在数据库里的图片字段 自己的数据访问请替换下面的
string cxnstr = System.Configuration.ConfigurationManager.ConnectionStrings["db"].ConnectionString;
SqlConnection connection = new SqlConnection(cxnstr);
string query = "select largeimage from images where id=@id";
SqlCommand command = new SqlCommand(query, connection);
SqlParameter param0 = new SqlParameter("@id", SqlDbType.Int);
param0.Value = request.QueryString["ImageID"];
command.Parameters.Add(param0);
connection.Open();
Stream output = response.OutputStream;
byte[] d = ((byte[])(command.ExecuteScalar()));
output.Write(d, 0, d.Length);
connection.Close();
response.End();
}
}
代码大致如此.
3)前台调用:
avatarImage.ImageUrl = "AvatarImagefetch.ashx?id=" + user.id.ToString();
如有不明白,欢迎进QQ群讨论,QQ群:149385300.