saving-html-5-canvas-as-image-on-the-server-using-aspnet
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.fillRect(0, 0, 200, 200);
context.strokeStyle = "Green";
context.arc(150, 100, 50, 20, Math.PI * 2, false);
// Send the canvas image to the server. $(function() { $("#btnSave").click(function() { var image = document.getElementById("myCanvas").toDataURL("image/png"); image = image.replace('data:image/png;base64,', ''); $.ajax({ type: 'POST', url: 'CanvasSave.aspx/UploadImage', data: '{ "imageData" : "' + image + '" }', contentType: 'application/json; charset=utf-8', dataType: 'json', success: function(msg) { alert('Image saved successfully !'); } }); }); });
Default.aspx.cs
using System;
using System.IO;
using System.Web.Script.Services;
using System.Web.Services;
[ScriptService]
public partial class _Default : System.Web.UI.Page
{
static string path = @"F:\Dinesh\";
[WebMethod()]
public static void UploadImage(string imageData)
{
string fileNameWitPath = path + DateTime.Now.ToString().Replace("/", "-").Replace(" ", "- ").Replace(":", "") + ".png";
using (FileStream fs = new FileStream(fileNameWitPath, FileMode.Create))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
byte[] data = Convert.FromBase64String(imageData);
bw.Write(data);
bw.Close();
}
}
}
}
Now, drawShapes() is working and I can see the graphics in canvas when view in browser. But when I click the button to save that canvas image in folder nothing is happen. How can I save that canvas image in my folder?
Dinesh AmbaliyaPosted Oct 19, 2012, 6:45 AM
$.ajax({
type: 'POST',
url: 'CanvasSave.aspx/UploadImage', //correction:- url: 'Default.aspx/UploadImage'.
data: '{ "imageData" : "' + image + '" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(msg) {
alert('Image saved successfully !');
}
});