ASP.NET Send Canvas to Server as File Using Ajax

HTML 5 introduces canvas element as a resolution-dependent bitmap canvas which can be used for rendering graphs, game graphics, or other visual images on the fly. A canvas is a rectangle in your page where you can use JavaScript to draw anything you want. Below is the code save graphics drawn on Canvas to server through AJAX and ASP.NET.

ASPX Code


// First convert to data URL
var dataURL = <%=canvas.ClientID%>.toDataURL();

// Now Post through AJAX
$.ajax({

	type: "POST",
	url: "upload.aspx",
	data: { image: dataURL }
	}).done(function(filename) {
	alert(filename);
});


Code behind (Upload.aspx.cs)


protected void Page_Load(object sender, EventArgs e)
{
	string mImage = Request["image"];
	string mFileName = System.Guid.NewGuid().ToString() + ".png";
	mImage = mImage.Split(new char[] { ',' })[1];
	byte[] mImageArr = Convert.FromBase64String(mImage);
	System.IO.FileStream mFile = new System.IO.FileStream(Server.MapPath(".") + @"\uploadedimages\" + mFileName, System.IO.FileMode.CreateNew);
	mFile.Write(mImageArr, 0, mImageArr.Length);
	mFile.Flush();
	mFile.Close();
	mFile.Dispose();

	Response.Clear();
	Response.ContentType = "text/plain";
	Response.Write(mFileName);
	Response.End();
}

Leave a Reply

Your email address will not be published.