Hello,
Here is your complete code:
Server side(.cs file):
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "")
{
byte[] myimage = new byte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile Image = FileUpload1.PostedFile;
Image.InputStream.Read(myimage, 0,
(int)FileUpload1.PostedFile.ContentLength);
SqlConnection myConnection =
new SqlConnection("Data Source =RASHED-PC;Initial Catalog= TestDB; Integrated Security= true");
SqlCommand storeimage =
new SqlCommand("INSERT INTO Iamge_Gallery "
+ "(Img_Id, Image_Content, Image_Type, Image_Size) "
+ " values (4, @image, @imagetype, @imagesize)"
, myConnection);
storeimage.Parameters.Add("@image",
SqlDbType.Image, myimage.Length).Value = myimage;
storeimage.Parameters.Add("@imagetype", SqlDbType.VarChar, 100).Value
= FileUpload1.PostedFile.ContentType;
storeimage.Parameters.Add("@imagesize", SqlDbType.BigInt, 99999).Value
= FileUpload1.PostedFile.ContentLength;
myConnection.Open();
storeimage.ExecuteNonQuery();
myConnection.Close();
Response.Write("successfully upload the image");
GetImageFromDB();
}
}
private void GetImageFromDB()
{
byte[] myimage = new byte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile Image = FileUpload1.PostedFile;
Image.InputStream.Read(myimage, 0,
(int)FileUpload1.PostedFile.ContentLength);
string connStrName="Data Source =RASHED-PC;Initial Catalog= TestDB; Integrated Security= true";
string storeimage ="SELECT [Img_Id],[Image_Content],[Image_Type],[Image_Size]FROM [TestDB].[dbo].[Iamge_Gallery]";
DataTable dt = new DataTable();
SqlDataReader dr = null;
using (SqlConnection conn = new SqlConnection(connStrName))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = storeimage;
cmd.CommandType = CommandType.Text;
conn.Open();
dr = cmd.ExecuteReader();
dt.Load(dr);
conn.Close();
cmd = null;
}
if (dt.Rows.Count>0)
{
BindApplicantImage((byte[])dt.Rows[0]["Image_Content"]);
}
Response.Write("successfully upload the image");
}
private void BindApplicantImage(byte[] applicantImage)
{
string base64ImageString = ConvertBytesToBase64(applicantImage);
imgBox.ImageUrl = "data:image/jpg;base64," + base64ImageString;
}
public string ConvertBytesToBase64(byte[] imageBytes)
{
return Convert.ToBase64String(imageBytes);
}
Client Side:
<form id="form1" runat="server">
<asp:fileupload id="FileUpload1" runat="server" xmlns:asp="#unknown">
<asp:button id="Button1" text="Upload Image" runat="server" onclick="Button1_Click" xmlns:asp="#unknown">
<asp:image id="imgBox" width="200px" height="200px" imageurl="" runat="server" xmlns:asp="#unknown">
</form>