以前我在将图像插入sql数据库时遇到了问题。现在我已经解决了这个问题,并能够在sqldatabase中插入图像。现在我遇到从数据库表中检索图像的问题。这是我的检索代码:
showimage.ashx:
<%@ WebHandler Language="C#" Class="ShowImage" %>
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";**
获取异常“未指定参数”
请帮助我如何从数据库表中检索图像。 这是我的GUI:
<asp:Label ID="lblEmpName" runat="server" Text="Employee Name"></asp:Label>
<asp:TextBox ID="txtEName" runat="server"></asp:TextBox>
<br />
<asp:Label ID="lblImage" runat="server" Text="Employee Image"></asp:Label>
<asp:FileUpload ID="imgUpload" runat="server" />
<br />
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
onclick="btnSubmit_Click" />
 
<asp:Label ID="lblResult" runat="server" ForeColor="#0066FF"></asp:Label>
<br />
<hr />
<asp:Image ID="Image1" style="width:200px" Runat="server"/>
答案 0 :(得分:1)
你看到的例外实际上是上面一行抛出的例外:
throw new ArgumentException("No parameter specified");
即。因为您的请求没有empid
查询字符串而导致:
somepage.aspx?empid=42
除此之外,我的代码中看不到任何明显错误。
答案 1 :(得分:0)
你得到的错误消息,看起来像是因为Kragen指出要消失。
我认为您可以大大简化代码:
为什么不直接返回字节数组?
此链接也可以为您提供帮助:http://www.worldofasp.net/tut/images/Displaying_images_in_ASPNET_using_HttpHandlers_92.aspx