Save Image Data from Syncfusion ImageEditor in ASP.NET Core using AJAX
This guide demonstrates how to save image base64 data from the Syncfusion Image Editor to a server using AJAX in an ASP.NET Core application.
Prerequisites
- Syncfusion Essential JS 2
- ASP.NET Core environment setup
Implementation Steps
1. Set up the ImageEditor in the View
First, include the Syncfusion ImageEditor in your view file, typically Index.cshtml
. Add a button that will trigger the save action.
<!-- Index.cshtml -->
<ejs-button id="image" cssClass='e-primary' content="Save Image"></ejs-button>
<div class="col-lg-12 control-section e-img-editor-sample">
<ejs-imageeditor id="image-editor"></ejs-imageeditor>
</div>
2. Add JavaScript to Handle Button Click
When the “Save Image” button is clicked, the following JavaScript function will be executed. It retrieves the image data from the ImageEditor, converts it to a base64 URL, and sends it to the server using AJAX.
<script>
document.getElementById('image').onclick = function () {
var imageEditorObj = ej.base.getComponent(document.getElementById('image-editor'), 'image-editor');
var imageData = imageEditorObj.getImageData();
const canvas = document.createElement('canvas');
canvas.width = imageData.width;
canvas.height = imageData.height;
const context = canvas.getContext('2d');
context.putImageData(imageData, 0, 0);
var base64Url = canvas.toDataURL();
$.ajax({
type: "POST",
url: "/Home/getImageData",
data: { imageData: base64Url },
success: function (data) {
console.log("success");
}
});
}
</script>
3. Create the Server-Side Handler
In your HomeController.cs
, add a method to handle the AJAX POST request. This method will receive the base64 encoded image data.
// HomeController.cs
[HttpPost]
public void getImageData(string imageData)
{
Console.WriteLine(imageData);
}
Additional References
- Syncfusion ImageEditor Documentation: ImageEditor Component
- jQuery AJAX Documentation: jQuery.ajax()
- HTML5 Canvas API: CanvasRenderingContext2D.putImageData()
By following these steps, you can successfully save image data from the Syncfusion ImageEditor to your server for further processing or storing it in database.