0

我正在尝试使数据库中的图像出现在 Web 表单上的图像按钮上。没有错误消息,但图像没有出现。只有一个小的指示出现在图像按钮上,而不是来自数据库的图像....

我的处理程序在这里:

public void ProcessRequest (HttpContext context)
{
        Int32 Member_No;
        if (context.Request.QueryString["id"] != null)
        {
            Member_No = Convert.ToInt32(context.Request.QueryString["id"]);
            context.Response.ContentType = "image/jpeg";

            Stream strm = ShowEmpImage(Member_No);

            byte[] buffer = new byte[4096];
            int byteSeq = strm.Read(buffer, 0, 4096);

            while (byteSeq > 0)
            {
                context.Response.OutputStream.Write(buffer, 0, byteSeq);
                byteSeq = strm.Read(buffer, 0, 4096);
            }  
        }
        else
        {
            context.Response.Write("No Image Found");
        }
    }

   public bool IsReusable
   {
       get
       {
           return false;
       }
   }

   public Stream ShowEmpImage(int Member_No) 
   {
       SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyServer"].ConnectionString);
       con.Open();
       SqlCommand cmd = new SqlCommand("Select Photo from Members where Member_No = @ID", con);
       cmd.CommandType = CommandType.Text;
       cmd.Parameters.AddWithValue("@ID", Member_No);

       object img = cmd.ExecuteScalar();

       try
       {
           return new MemoryStream((byte[])img);
       }
       catch
       {
           return null;
       }
       finally
       {
           con.Close();
       }
   }
}
4

1 回答 1

0

我只会返回byte[]from 执行标量并将字节写入流。

public byte[] ShowEmpImage(int Member_No) 
{
   var settings = ConfigurationManager.ConnectionStrings["MyServer"];
   using(var con = new SqlConnection(settings.ConnectionString))
   using(var cmd = new SqlCommand("Select Photo from Members where Member_No = @ID", con))
   {
       con.Open();
       cmd.CommandType = CommandType.Text;
       cmd.Parameters.AddWithValue("@ID", Member_No);

       return (byte[])cmd.ExecuteScalar();
   }
}

var image = ShowEmpImage(Member_No);
context.Response.WriteBytes(image);
context.Response.ContentType = "image/jpg";

顺便说一句:我还将您的 ado.net 组件包装在using块中以防止内存泄漏。

于 2012-09-26T14:07:49.783 回答