Hi Amitabha,
Check this example. Now please take its reference and correct your code.
HTML
<asp:Image ID="DrvImage" runat="server" />
<asp:Button Text="Save" runat="server" OnClick="OnSave" />
Namespaces
C#
using System.Configuration;
using System.Data.SqlClient;
using System.IO;
VB.Net
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.IO
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
byte[] bytes = Convert.FromBase64String("R0lG...");
DrvImage.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(bytes);
}
}
protected void OnSave(object sender, EventArgs e)
{
string fileName = DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".jpg";
string filePath = "~/Uploads/" + fileName;
string base64Image = DrvImage.ImageUrl.Replace("data:image/jpeg;base64,", "");
byte[] bytes = Convert.FromBase64String(base64Image);
File.WriteAllBytes(Server.MapPath(filePath), bytes);
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection conn = new SqlConnection(constr))
{
string sql = "INSERT INTO Files VALUES(@Name, @Path)";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("@Name", fileName);
cmd.Parameters.AddWithValue("@Path", filePath);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
Response.Redirect(Request.Url.AbsoluteUri);
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
Dim bytes As Byte() = Convert.FromBase64String("R0lG...")
DrvImage.ImageUrl = "data:image/jpeg;base64," & Convert.ToBase64String(bytes)
End If
End Sub
Protected Sub OnSave(ByVal sender As Object, ByVal e As EventArgs)
Dim fileName As String = DateTime.Now.ToString("ddMMyyyy_HHmmss") & ".jpg"
Dim filePath As String = "~/Uploads/" & fileName
Dim base64Image As String = DrvImage.ImageUrl.Replace("data:image/jpeg;base64,", "")
Dim bytes As Byte() = Convert.FromBase64String(base64Image)
File.WriteAllBytes(Server.MapPath(filePath), bytes)
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using conn As SqlConnection = New SqlConnection(constr)
Dim sql As String = "INSERT INTO Files VALUES(@Name, @Path)"
Using cmd As SqlCommand = New SqlCommand(sql, conn)
cmd.Parameters.AddWithValue("@Name", fileName)
cmd.Parameters.AddWithValue("@Path", filePath)
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
End Using
End Using
Response.Redirect(Request.Url.AbsoluteUri)
End Sub
Note : Change base64 string with the database data.