Asp.net C# Tutorial 29-How to Upload Image into Database & display Image from Database in ASP.NET C#

Published: 16 February 2023
on channel: Chirags Tutorial
1,730
17

Web.config

<connectionStrings>
<add name="conString" connectionString="Data Source=localhost;Initial Catalog=Chirags_ImagesUploadRetrieveFromSQLDatabase;User Id=sa;Password=admin@123" providerName="System.Data.SqlClient" />
</connectionStrings>

*******************************************************
--db table code script
CREATE TABLE [dbo].[images](
[image_id] [int] IDENTITY(1,1) NOT NULL,
[photo] [image] NULL
);

************************************************
PhotoHandler.ashx

<%@ WebHandler Language="C#" Class="PhotoHandler" %>

using System;
using System.Web;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;

public class PhotoHandler : IHttpHandler {

public void ProcessRequest (HttpContext context) {
string image_id = context.Request.QueryString["image_id"].ToString();
string qr = "select photo from [images] where image_id=" + image_id;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand(qr, con);
SqlDataAdapter ad = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
ad.Fill(ds);
con.Close();
context.Response.ContentType = "application/Image";
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + context.Request.QueryString[0].ToString());
byte[] myphoto = (byte[])ds.Tables[0].Rows[0]["photo"];
context.Response.BinaryWrite(myphoto);
}

public bool IsReusable {
get {
return false;
}
}

}

*****************************************************
Default.aspx



<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<table style="margin-left:auto;margin-right:auto;">
<tr>
<td>
Image Upload : <asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="sbtBtn" runat="server" Text="Submit" OnClick="sbtBtn_Click" />
</td>
</tr>
</table>
<table style="margin-left:auto;margin-right:auto;">
<tr>
<td>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="image_id" HeaderText="Image Id" />
<asp:TemplateField HeaderText="Photo">
<ItemTemplate>
<asp:Image Width="100px" ID="Image1" ImageUrl='<%# String.Format("~/PhotoHandler.ashx?image_id={0}",Eval("image_id")) %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</form>
</body>
</html>


***********************************************
Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conString"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
//GridView1.PreRender += new EventHandler(GridView1_PreRender);
bind();
}
public void bind()
{
con.Open();
string query = "select * from [images]";
SqlCommand cmd = new SqlCommand(query,con);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
con.Close();
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
// using this pre render for hide the header text line if we dont have any data.
//protected void GridView1_PreRender(object sender, EventArgs e)
//{
// if (GridView1.Rows.Count >0)
// {
// GridView1.UseAccessibleHeader = true;
// GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;
// }
//}

protected void sbtBtn_Click(object sender, EventArgs e)
{
byte[] myphoto = FileUpload1.FileBytes;
if (con.State == ConnectionState.Closed)
con.Open();
string insertUplod = "Insert into [images] (photo) values (@pic)";
SqlCommand insertCmd = new SqlCommand(insertUplod, con);
insertCmd.Parameters.AddWithValue("@pic",myphoto);
insertCmd.ExecuteNonQuery();
con.Close();
}
}


Watch video Asp.net C# Tutorial 29-How to Upload Image into Database & display Image from Database in ASP.NET C# online without registration, duration hours minute second in high quality. This video was added by user Chirags Tutorial 16 February 2023, don't forget to share it with your friends and acquaintances, it has been viewed on our site 1,730 once and liked it 17 people.