Save image to database : Image Saving « ADO.net Database « ASP.NET Tutorial






<%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<script runat="server">

void UploadImage(Object sender, EventArgs e)
{
  String connectionString = "Enter your Connection String";
  Stream imageStream = ImageFile.PostedFile.InputStream;
  Byte[] byteData = new Byte[ImageFile.PostedFile.ContentLength];
  SqlConnection objConn = new SqlConnection(connectionString);
  SqlCommand objCommand = new SqlCommand("INSERT INTO sql_images(Image) VALUES(@image)", objConn);
  SqlParameter objParam = new SqlParameter("@image", SqlDbType.Image);

  imgStream.Read(imgdata, 0, ImageFile.PostedFile.ContentLength);
  objParam.Value = imgdata;
  objCommand.Parameters.Add(imgparam);

  try
  {
    objConn.Open();
    objCommand.ExecuteNonQuery();
  } 
  catch (System.Exception exc)
  {
    ErrorLabel.Text = exc.ToString();
  }
  finally
  {
    objConn.Close();
    imgStream.Close();
  }
}
</script>
<form enctype="multipart/form-data" runat="server">
  <input id="imageFile" runat="server" type="file" />
    <asp:button runat="server" OnClick="UploadImage" Text="Upload" />
  <asp:Label id="ErrorLabel" runat="server" />
</form>








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