Articles → .NET → Storing And Retrieving Image From Database In Asp.Net

Storing And Retrieving Image From Database In Asp.Net






Example




  1. A file upload control for selecting the image.
  2. A button ‘Save’ to save selected image in the database table.
  3. An image box to display an image.
  4. A button ‘View Image’ to retrieve image from database table and display in the image box.

Table Schema




Picture showing the table schema of the sample table in database
Click to Enlarge


Code


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Index.aspx.cs" Inherits="Index" %>
<!DOCTYPE html>
<html
	xmlns="http://www.w3.org/1999/xhtml">
	<head runat="server">
		<title></title>
	</head>
	<body>
		<form id="form1" runat="server">
        Select Image
        
			<asp:FileUpload ID="FileUpload1" runat="server" />
			<br />
			<asp:Button ID="BtnSave" runat="server" Text="Save" OnClick="BtnSave_Click"></asp:Button>
			<asp:Button ID="BtnView" runat="server" Text="View Image" OnClick="BtnView_Click"></asp:Button>
			<br />
			<asp:Image ID="Image1" runat="server" Visible="false" length="200px" Width="200px" />
		</form>
	</body>
</html>


using System;
using System.Configuration;
using System.Data.SqlClient;
using System.IO;

public partial class Index: System.Web.UI.Page {
  protected void BtnSave_Click(object sender, EventArgs e) {
    int length = FileUpload1.PostedFile.ContentLength;
    byte[] pic = new byte[length];
    FileUpload1.PostedFile.InputStream.Read(pic, 0, length);
    using(SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["image"].ToString())) {
      con.Open();
      SqlCommand com = new SqlCommand("insert into Image " +
        "(Photo) values (@Photo)", con);
      com.Parameters.AddWithValue("@Photo", pic);
      com.ExecuteNonQuery();
    }
  }

  protected void BtnView_Click(object sender, EventArgs e) {
    using(SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["image"].ToString())) {
      con.Open();
      SqlCommand comPhoto = new SqlCommand("Select top 1 Photo From Image", con);
      byte[] bytes = (byte[]) comPhoto.ExecuteScalar();
      string filePath = "~/Files/Test.jpg";
      File.WriteAllBytes(Server.MapPath(filePath), bytes);
      Image1.ImageUrl = filePath;
      Image1.Visible = true;
    }
  }
}



Output


Picture showing the output of Storing and retrieving Image from database in asp.net
Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Wednesday, July 12, 2017

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250