Thursday, February 18, 2010

ASP.Net Page to Return an Image from an SQL

protected void Page_Load(object sender, EventArgs e)
{
string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["ProductCatalogueConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
string blobId = Request.QueryString["ID"];
if (!string.IsNullOrEmpty(blobId))
{
string cmdText = "select A.blob from Core.Attachment A where A.AttachmentID = '" + blobId + "'";
conn.Open();
SqlCommand cmd = new SqlCommand(cmdText, conn);
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (reader.Read())
{
byte[] imgBytes = (byte[])reader["blob"];
Response.ContentType = "image/jpeg";
Response.BinaryWrite(imgBytes);
}
}
}

No comments: