我在图像列中有二进制数据,我需要检索图像并显示它。所以我添加了一个ashx文件,在aspx文件中我有一个文本框用于图像名称和一个文件上载控件。图像已成功插入,但我认为(我很确定)ashx文件中有问题,但无法找到。我没有任何例外。它只是不起作用。
这是我的代码:
protected void butSubmit_Click(object sender, EventArgs e)
{
byte[] imgbyte = null;
if (FileUpload1.HasFile && FileUpload1.PostedFile != null)
{
HttpPostedFile file = FileUpload1.PostedFile;
imgbyte = new byte[file.ContentLength];
file.InputStream.Read(imgbyte, 0, file.ContentLength);
}
SqlConnection connection = new SqlConnection(@"server=.\sqlexpress;database=projects;Uid=sa;Password=1234");
connection.Open();
SqlCommand cmd = new SqlCommand("Insert imgtable values(@title,@image) select @@IDENTITY",connection);
cmd.Parameters.AddWithValue("@title",txtTitle.Text);
cmd.Parameters.AddWithValue("@image", imgbyte);
int id = Convert.ToInt32(cmd.ExecuteScalar());
Image1.ImageUrl = "~/Handler.ashx?id=" + id;
connection.Close();
}
这是通用处理程序文件:
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if(context.Request.QueryString["id"]!=null)
{
int id=Convert.ToInt32(context.Request.QueryString["id"]);
Stream stream = DisplayImage(id);
context.Response.ContentType = "image/jpeg";
byte[]img=new byte[stream.Length];
context.Response.OutputStream.Write(img, 0, img.Length);
}
}
public Stream DisplayImage(int theID)
{
SqlConnection con=new SqlConnection (@"server=.\sqlexpress;database=projects;Uid=sa;Password=1234");
SqlCommand cmd=new SqlCommand ("select image from imgtable where id=@id",con);
con.Open();
cmd.Parameters.AddWithValue("@id",theID);
byte[] img = (byte[])cmd.ExecuteScalar();
con.Close();
return new MemoryStream(img);
}
public bool IsReusable
{
get
{
return false;
}
}
}
答案 0 :(得分:1)
您正在使用流的长度初始化一个新的字节数组,但该字节数组中没有任何内容。我在谈论ProcessRequest中的img字节数组。使DisplayImage方法返回字节数组并直接使用它。如果DisplayImage中的img中包含数据,还要检查调试器。
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if(context.Request.QueryString["id"]!=null)
{
int id=Convert.ToInt32(context.Request.QueryString["id"]);
byte[] img = DisplayImage(id);
context.Response.ContentType = "image/jpeg";
context.Response.OutputStream.Write(img, 0, img.Length);
}
}
public byte[] DisplayImage(int theID)
{
SqlConnection con=new SqlConnection (@"server=.\sqlexpress;database=projects;Uid=sa;Password=1234");
SqlCommand cmd=new SqlCommand ("select image from imgtable where id=@id",con);
con.Open();
cmd.Parameters.AddWithValue("@id",theID);
byte[] img = (byte[])cmd.ExecuteScalar();
con.Close();
return img;
}
public bool IsReusable
{
get
{
return false;
}
}
}