Read image from database and send to client : Image Saving « ADO.net Database « ASP.NET Tutorial






<%@ Page %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.IO" %>
<script runat="server" language="C#">
void Page_Load(Object sender, EventArgs e)
{
  string connectionString = "Data Source=myServer;Initial Catalog=myCatalog;User Id=user;Password=pass";
  SqlConnection objConnection = new SqlConnection(connectionString);
  string commandText = "SELECT Image FROM imageTable";
  SqlCommand objCommand = new SqlCommand(commandText, objConnection);
  SqlDataReader objReader = null;
      
  try {
    objConnection.Open();
    objReader = objCommand.ExecuteReader();
    
    if (objReader.Read()) 
    {
      Response.ContentType = "image/jpeg";
      Response.BinaryWrite((Byte[])objReader["Image"]);
    }
  } catch (Exception exc) 
  {
    Response.Write(exc.Message);
    Response.Write("<br>This page would display an image if its connection string were set up.");
  } 
  finally 
  {
    if ((objConnection != null) && (objConnection.State == ConnectionState.Open)) 
    {
      objConnection.Close();
    }
    if (objReader != null)
    objReader.Close();
  }
}
</script>








18.49.Image Saving
18.49.1.Save image to database
18.49.2.Read image from database and send to client