Hi RichardSa,
You need to use jQuery Ajax if you do not want to use HiddenField and Server.MapPath.
Please refer the sample below.
HTML
<div>
<div class="tools">
<a href="#colors_sketch" data-tool="marker">Marker</a>
<a href="#colors_sketch" data-tool="eraser">Eraser</a>
</div>
<br />
<canvas id="colors_sketch" width="300px" height="100px"></canvas>
<br /><br />
<asp:Button ID="btnSave" Text="Save Image" runat="server" />
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.rawgit.com/mobomo/sketch.js/master/lib/sketch.min.js"></script>
<script type="text/javascript">
$(function () {
$(".tools a").click(function () {
$('#colors_sketch').sketch();
$(".tools a").eq(0).attr("style", "color:#000");
$(".tools a").removeAttr("style");
$(this).attr("style", "color:#000");
});
$('#btnSave').bind("click", function () {
var base64 = $('#colors_sketch')[0].toDataURL();
$.ajax({
type: "POST",
url: "Default.aspx/InsertImage",
data: '{base64: "' + base64 + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) { alert(response.d); },
error: function (response) { alert(response.responseText); }
});
return false;
});
});
</script>
Namespaces
C#
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web.Services;
VB.Net
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports System.IO
Imports System.Web.Services
Code
C#
[WebMethod]
public static string InsertImage(string base64)
{
byte[] bytes = Convert.FromBase64String(base64.Split(',')[1]);
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO [tblFiles] (Name, ContentType, Data) VALUES (@Name, @ContentType, @Data)"))
{
cmd.Parameters.AddWithValue("@Name", "Test.png");
cmd.Parameters.AddWithValue("@ContentType", "image/png");
cmd.Parameters.AddWithValue("@Data", bytes);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
return "Uploaded Successfully!";
}
VB.Net
<WebMethod()>
Public Shared Function InsertImage(ByVal base64 As String) As String
Dim bytes As Byte() = Convert.FromBase64String(base64.Split(","c)(1))
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand("INSERT INTO [tblFiles] (Name, ContentType, Data) VALUES (@Name, @ContentType, @Data)")
cmd.Parameters.AddWithValue("@Name", "Test.png")
cmd.Parameters.AddWithValue("@ContentType", "image/png")
cmd.Parameters.AddWithValue("@Data", bytes)
cmd.Connection = con
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
Return "Uploaded Successfully!"
End Function