In this article I will explain with an example, how to upload (save) HTML5 Canvas Image to Server in Folder (Directory) in ASP.Net Core Razor Pages.
The jQuery Sketch plugin will be used to allow users to draw Signatures and later the HTML5 Canvas Image of the Signature will be uploaded to Server and saved as Image in Folder (Directory).
Note: For more details on ASP.Net Core Razor Pages, please refer my article ASP.Net Core 7 Razor Pages: Hello World Tutorial with Sample Program example.
 
 
File Location
The HTML5 Canvas Image will be saved in the Files Folder (Directory) of wwwroot Folder (Directory).
ASP.Net Core Razor Pages: Upload (Save) HTML5 Canvas Image to Server in Folder (Directory)
 
 
Namespaces
You will need to import the following namespaces.
using System.IO;
using Microsoft.AspNetCore.Hosting;
 
 
Razor PageModel (Code-Behind)
The PageModel consists of the following Handler methods.
Handler method for handling GET operation
This Handler method is left empty as it is not required.
 
Handler method for handling POST operation
When Save Button is clicked this Handler method gets called which accepts Base64 string as a parameter.
Then, the Base64 string is converted into a Byte Array.
A check is performed whether the Folder (Directory) for saving the HTML5 Canvas Image exists, if not then the Folder (Directory) is created inside the wwwroot using IWebHostEnvironment interface.
Note: The IWebHostEnvironment interface is injected using Dependency Injection inside the IndexModel class, for more details please refer Using IWebHostEnvironment in ASP.Net Core.
           For more details on how to access Static Files in Core, please refer my article Static Files (Images, CSS and JS files) in ASP.Net Core.
 
Finally, the Byte Array is saved as Image file in Folder (Directory) using WriteAllBytes method of File class.
public class IndexModel : PageModel
{
    private IWebHostEnvironment Environment;
 
    public IndexModel(IWebHostEnvironment _environment)
    {
        this.Environment = _environment;
    }
 
    public void OnGet()
    {
    }
 
    public void OnPostSave(string imageData)
    {
        string base64 = imageData.Split(',')[1];
 
        //Convert Base64 string to Byte Array.
        byte[] bytes = Convert.FromBase64String(base64);
 
        string folderPath = Path.Combine(this.Environment.WebRootPath, "Files");
 
        if (!Directory.Exists(folderPath))
        {
            Directory.CreateDirectory(folderPath);
        }
 
        //Save the Byte Array as Image File.
        System.IO.File.WriteAllBytes(string.Format("{0}\\{1}.png", folderPath, Path.GetRandomFileName()), bytes);
    }
}
 
 
Razor Page(HTML)
Inside the HTML of Razor Page, the ASP.Net TagHelpers is inherited.
The HTML of Razor Page consists of an HTML Form which has been created using the ASP.Net TagHelpers with the following attribute.
method – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The following HTML Form consists of an HTML DIV consisting of two HTML Anchor elements for selecting Marker and Eraser for the HTML5 Canvas Sketchpad and an HTML5 Canvas element.
There is also an Input Hidden Field and a Button. The Hidden Field will be used to save the HTML5 Canvas Image as Base64 string.
The Submit Button has been set with the POST Handler method using the asp-page-handler attribute.
Note: In the Razor PageModel, the Handler method name is OnPostSave but here it will be specified as Save when calling from the Razor HTML Page.
 
The Submit Button has also been assigned JavaScript onclick event handler to call the ConvertToImage JavaScript function.
 
jQuery Sketch plugin implementation
Inside the Razor Page,the following jQuery and Sketch JS files are inherited.
1. jquery.min.js
2. sketch.min.js
Inside the jQuery document ready event handler, the jQuery Sketch plugin is applied to the HTML5 Canvas element.
Anchor element for selecting Marker is applied with the Style .i.e. (color:#000) and when any of the Anchor link is clicked the Style is removed from the Anchor elements and applied to only that element which was clicked.
 
ConvertToImage
Inside the ConvertToImage JavaScript function, the HTML5 Canvas Image is converted into Base64 string using toDataURL method and then saved into the Hidden Field.
 
Submitting the Form
When the Submit button is clicked, the Form is submitted to the POST Handler method.
@page
@model Upload_Sketch_Server_Core_Razor.Pages.IndexModel
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/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 () {
            $('#colors_sketch').sketch();
            $(".tools a").eq(0).attr("style", "color:#000");
            $(".tools a").click(function () {
                $(".tools a").removeAttr("style");
                $(this).attr("style", "color:#000");
            });
        });
        function ConvertToImage() {
            $("[id*=hfImageData]").val($('#colors_sketch')[0].toDataURL());
        };
    </script>
</head>
<body>
    <form method="post">
        <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="500" height="200" style="border: 1pxsolid;"></canvas>
        <br />
        <input type="hidden" ID="hfImageData" name="imageData" />
        <input type="submit" value="Save" onclick="ConvertToImage()" asp-page-handler="Save" />
    </form>   
</body>
</html>
 
 
Screenshot
Creating Signature and saving
ASP.Net Core Razor Pages: Upload (Save) HTML5 Canvas Image to Server in Folder (Directory)
 
Uploaded HTML5 Canvas Image
ASP.Net Core Razor Pages: Upload (Save) HTML5 Canvas Image to Server in Folder (Directory)
 
 
Demo
 
 
Downloads