从sql数据库中检索图像

以前我有插入图像到SQL数据库的问题。 现在我已经解决了这个问题,并能够在sqldatabase中插入图像。 现在我遇到从数据库表中检索图像的问题。 这是我的检索代码:

showimage.ashx:  using System; using System.Web; using System.IO; using System.Configuration; using System.Data.SqlClient; using System.Data; public class ShowImage : IHttpHandler { public void ProcessRequest (HttpContext context) { int empno; if (context.Request.QueryString["empid"] != null) empno = Convert.ToInt32(context.Request.QueryString["id"]); else throw new ArgumentException("No parameter specified"); context.Response.ContentType = "image/jpeg"; //context.Response.Write("Hello World"); Stream strm = ShowEmpImage(empno); 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); } } public Stream ShowEmpImage(int empno) { string conn = ConfigurationManager.ConnectionStrings["EmployeeConnString"].ConnectionString; SqlConnection connection = new SqlConnection(conn); string sql = "SELECT empimg FROM EmpDetails WHERE empid = @ID"; SqlCommand cmd = new SqlCommand(sql, connection); cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@ID", empno); connection.Open(); object img = cmd.ExecuteScalar(); try { return new MemoryStream((byte[])img); } catch { return null; } finally { connection.Close(); } } public bool IsReusable { get { return false; } } } 

在这一行:

 **context.Response.ContentType = "image/jpeg";** 

得到exception“没有指定参数”

请帮助我如何从数据库表中检索图像。 这是我的GUI:

        
    

       &nbsp

您看到的例外实际上是上面一行抛出的exception:

 throw new ArgumentException("No parameter specified"); 

即因为您的请求没有empid查询字符串而导致:

 somepage.aspx?empid=42 

除此之外,我无法在您的代码中看到任何其他明显错误的内容。

你得到的错误消息,看起来是由于Kragen指出的消失。

我认为你可以大大简化你的代码:

  • 您有一个转换为字节数组的对象
  • 然后使用字节数组创建流
  • 然后,您将流转换为字节数组。

为什么不返回字节数组?

此链接也可以帮助您: http : //www.worldofasp.net/tut/images/Displaying_images_in_ASPNET_using_HttpHandlers_92.aspx