如何使用c#从数据库中检索多个图像
我有一个9个图像的数据库,它不断变化,所以我不能直接在html 标签中设置
src
来显示9个图像,我必须从数据库中选择它们并相应地绑定它们。
我能够使用Response.BinaryWrite()
检索和打印1个图像,但不是全部9.我的byte[]
只获取db中的第一个图像,
这是代码,
while (dr.Read()) { Response.ContentType = "image/jpg"; Response.BinaryWrite((byte[])(dr["fsImage"])); }
如何检索所有9个图像,以及如何将它们绑定到标记或动态构造html
标记
我是新手,所以如果有愚蠢的错误,请放轻松我;)
提前致谢。
您无法让网页提供所有图像的内容。
为了“动态”渲染图像,您需要制作一个可以为您提供单个图像的页面。 此页面将使用您上面的代码。
然后选择哪个图像显示页面的URL会发生变化
http://youdomain/makeimage.aspx?imageid=1
和
http://youdomain/makeimage.aspx?imageid=2
然后,make image中的代码将返回单个图像。
注意 – 如果你制作url,你会更开心
http://youdomain/makeimage.aspx?imageid=1&mytype=.jpg
因此,使图像url在扩展名中结束。 一些浏览器(IE)作弊并查看字符串的结尾以查看期望的内容类型。 他们将使用上面的url,但不是没有试用.jpg。
此外,您需要实现某种forms的缓存,我们的性能将是一只狗(特别是如果您尝试扩展)。
祝好运。
使用HttpHandler并调用Img标记
一个例子
<%@ WebHandler Language="C#" Class="Handler2" %> using System; using System.Web; using System.Data.SqlClient; using System.Data; using System.Configuration; public class Handler2 : IHttpHandler { public void ProcessRequest(HttpContext context) { if (context.Request.QueryString["pid"] != null) { string ID = context.Request.QueryString["pid"].ToString(); if (dt.Rows.Count > 0) { int pid = Convert.ToInt32(ID); SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString); myConnection.Open(); //int i = Convert.ToInt32(context.Request.QueryString["id"]); string sql = "Select BackGroundImage from Wall_BackgrndImg_Master where FK_Company_Master=@ImageId"; SqlCommand cmd = new SqlCommand(sql, myConnection); cmd.Parameters.Add("@ImageId", SqlDbType.Int).Value = pid; cmd.Prepare(); SqlDataReader dr = cmd.ExecuteReader(); dr.Read(); try { context.Response.ContentType = "jpg"; context.Response.BinaryWrite((byte[])dr["BackGroundImage"]); dr.Close(); myConnection.Close(); } catch { } } } } public bool IsReusable { get { return false; } } }
并打电话给