2013-03-19 71 views
1

我需要帮助将存储在我的数据库中的图像文件显示到 图像控件中。我已经阅读了一些文章,并观看了一些完美的视频教程,并且我遵循了它,但是我无法使其工作。图像控件只显示空白。我使用Generic Handler从我的数据库检索图像文件。请帮我指出我哪里出错了?感谢您的帮助......这里是我的代码。无法使用通用处理程序将我的数据库中的图像文件显示到图像控件中

通用处理器

<%@ WebHandler Language="C#" Class="ShowImage" %> 

using System; 
using System.Configuration; 
using System.Drawing; 
using System.Drawing.Imaging; 
using System.Web; 
using System.IO; 
using System.Data; 
using System.Data.SqlClient; 

public class ShowImage : IHttpHandler 
{ 

    public void ProcessRequest(HttpContext context) 
    { 
     if (context.Request.QueryString["ID"] == null) return; 
     //string connStr = ConfigurationManager.ConnectionStrings["connStr"].ToString(); 
     string connStr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Coldwind.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"; 
     string ID = context.Request.QueryString["ID"]; 


     using (SqlConnection conn = new SqlConnection(connStr)) 
     { 
      using (SqlCommand cmd = new SqlCommand("Select Photos From ProfileTab Where ID =" + ID, conn)) 
      { 
       //cmd.Parameters.Add(new SqlParameter("@ID",ID)); 
       conn.Open(); 
       using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection)) 
       { 
        reader.Read(); 
        context.Response.ContentType = "image/jpeg"; 
        context.Response.BinaryWrite((Byte[])reader[reader.GetOrdinal("Photos")]); 
        // byte[] imgData = (byte[])reader["Photos"]; 
        // context.Response.BinaryWrite(imgData); 
        reader.Close(); 
       } 
      } 
     } 
    } 


    public bool IsReusable 
    { 
     get 
     { 
      return true; 
     } 
    } 

} 

Asp.Net代码的图像控制

<asp:Image ID="Image1" runat="server" ImageUrl='<%# "ShowImage.ashx?ID=" + Eval("ID") %>' Height="128px" /> 
+0

不知道这.....“reader.GetOrdinal(”照片“)]”需要som e代码 – Prasad 2013-03-19 11:57:40

+0

我刚刚使用过,就像我在视频教程中看到的那样,它完美地工作在他们的最后,并且不要因为我正确地遵循它而无法在我的最终目标上工作。 – timmack 2013-03-19 12:00:54

回答

0

尝试MemoryStream的,因为这...

System.IO.MemoryStream dataStream = null; 
dataStream = new System.IO.MemoryStream(reader.GetOrdinal("Photos")); 
context.Response.ContentType = "image/jpeg"; 
dataStream.WriteTo(context.Response.OutputStream); 
dataStream.Close(); 
dataStream = null; 
+0

只需声明byte []并调试以查看它是否具有某个值或空格尝试使用 – Prasad 2013-03-19 12:32:18

+0

我试图使用类似这样的代码,但同样的事情,我确定它有数据,因为我的数据库列“Photos”显示。 – timmack 2013-03-19 12:39:47

+0

这是我尝试过的代码:context.Response.ContentType =“image/jpeg”; (“Byte [])reader [reader.GetOrdinal(”Photos“)]); byte [] imgData =(byte [])reader [”Photos“]; context.Response.BinaryWrite(imgData); – timmack 2013-03-19 12:41:02

相关问题