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

Опубликовано: 16 Февраль 2023
на канале: 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();
}
}


Смотрите видео Asp.net C# Tutorial 29-How to Upload Image into Database & display Image from Database in ASP.NET C# онлайн без регистрации, длительностью часов минут секунд в хорошем качестве. Это видео добавил пользователь Chirags Tutorial 16 Февраль 2023, не забудьте поделиться им ссылкой с друзьями и знакомыми, на нашем сайте его посмотрели 1,730 раз и оно понравилось 17 людям.