inchirags@gmail.com Chirag's ASP.NET C# Tutorial https://www.chirags.in
***********************************************************************************************
How to Upload Image into Database and display Image from Database in ASP.NET C#
***********************************************************************************************
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
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<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();
}
}
Note: Flow the Process shown in video.
Subscribe and like for more videos:
https://www.youtube.com/@chiragstutorial
Don't forget to, Follow, Like, Share & Comment
Thanks & Regards,
Chitt Ranjan Mahto "Chirag"
_____________________________________________________________________
Note: All scripts used in this demo will be available in our website.
Link will be available in description.