Retrieve image from database into a image tag
My web application allow user send report and also to insert up to 5
images into database (SQL Server) as varbinary(MAX). I am now finding a
way to retrieve all images of a particular report a user sent. Previously,
I used to retrieve image 1 by 1 through a aspx page. But I faced a problem
when the user only insert 1 image out of the 5. My 4 other image tag will
be displaying null image. So now I trying to find a method if I can
retrieve those images based on the report in just 1 image tag. Image was
stored in the same table as the report previously, now I change it to 2
table. MemberReport is all details of the report and MemberReportImage is
all the images of the report.
This code below allow me to retrieve the first image out of my
MemberReportImage table based on the memberreportid into a image tag,
however I wish to retrieve all the image with the same memberreportid at
once than into the image tag. As what I think it required a loop to get
all images but I not sure how to do. So I help someone to help me out on
this. THANKS!
protected void Page_Load(object sender, EventArgs e)
{
string strQuery = "select * from MemberReportImage where
memberreportid='" + Session["memberreportid"] + "'";
SqlCommand cmd = new SqlCommand(strQuery);
DataTable dt = GetData(cmd);
if (dt != null)
{
download(dt);
}
}
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch
{
return null;
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
}
private void download(DataTable dt)
{
// check if you have any rows at all
// no rows -> no data to convert!
if (dt.Rows.Count <= 0)
return;
// check if your row #0 even contains data -> if not, you can't do
anything!
if (dt.Rows[0].IsNull("image"))
return;
Byte[] bytes = (Byte[])dt.Rows[0]["image"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "image/jpg";
Response.BinaryWrite(bytes);
Response.End();
}
No comments:
Post a Comment