Here is the data table what I prepare .
create table tblStudent
(id int primary key identity(1,1),St_Photo image)
select * from tblStudent
SELECT St_Photo FROM tblStudent WHERE Id =1
DESIGN
create table tblStudent
(id int primary key identity(1,1),St_Photo image)
select * from tblStudent
SELECT St_Photo FROM tblStudent WHERE Id =1
DESIGN
ie
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SaveImage.aspx.cs" Inherits="SaveImage" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:FileUpload ID="fuPhoto" runat="server" />
<br />
<asp:HiddenField runat="server" ID="hfPhoto" Value="" />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
<asp:Button ID="btnShow" runat="server" Text="Show" OnClick="btnShow_Click" />
<asp:Image ID="imgShow" runat="server" />
</form>
</body>
</html>
CODE:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class SaveImage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (fuPhoto.HasFile)
{
byte[] bytesPhoto = null;
Stream fs = fuPhoto.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
bytesPhoto = br.ReadBytes(Convert.ToInt32(fs.Length));
SqlConnection sql = new SqlConnection(@"server=.;uid=sa;pwd=nic;database=master;");
sql.Open();
SqlCommand cmd = new SqlCommand("insert into tblStudent(St_Photo)values(@St_Photo)", sql);
cmd.Parameters.Add("@St_Photo", SqlDbType.Image).Value = bytesPhoto;
cmd.ExecuteNonQuery();
sql.Close();
}
}
protected void btnShow_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(@"server=.;uid=sa;pwd=nic;database=master;");
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("SELECT St_Photo FROM tblStudent WHERE Id =1",con);
sda.Fill(dt);
con.Open();
byte[] bytes = (byte[])dt.Rows[0][0];
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
imgShow.ImageUrl = "data:image/png;base64," + base64String;
}
}
No comments:
Post a Comment