325 views
asked in Asp.net C# by

How to Upload Image into Database & display Image from Database in ASP.NET C#

1 Answer

answered by

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.

Most popular tags

laravel postgresql laravel-10 replication ha postgresql mongodb laravel-11 mongodb database mongodb tutorial ubuntu 24.04 lts streaming-replication mysql database laravel postgresql backup laravel login register logout database mysql php laravel 11 - login with otp valid for 10 minutes. user and admin registration user and admin login multiauth technlogy asp.net asp.net c# mysql master slave replication centos linux laravel sql server schedule backup autobackup postgresql django python haproxy load balancer install self sign ssl laravel 11 gaurds zabbix 7 how to install graylog on ubuntu 24.04 lts | step-by-step asp.net core mvc .net mvc network upload c# ssl integration sql server on ubuntu 22.04 lts mssql server ms sql server sql server user access in postgres mysql password change cent os linux configure replica laravel 11 socialite login with google account google login kubernetes (k8s) install nginx load balancer install install and configure .net 8.0 in ubuntu 24.04 lts php in iis php with iis php tutorial chirags php tutorials chirags php tutorial chirags tutorial laravel 11 guards mongodb sharding metabase business analytics metabase postgresql 16 to postgresql 17 postgresql migration letsencrypt mongodb crud rocky linux laravel custom captcha laravel 11 captcha laravel captcha mongo dll php.ini debian 12 nginx apache nextcloud gitea in ubuntu git gitea npm error node js mysql ndb cluster mysql cluster ssl oracle login register logout in python debian windows shell batch file bat file time stamp date time shopping cart in laravel centos rhel swap memeory rhel 5.5
...