Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving HTML 5 Canvas as Image on the server using ASP.NET

Tags:

I need some help here..

Im trying to save a canvas image after drawing..

following this example (http://www.dotnetfunda.com/articles/article1662-saving-html-5-canvas-as-image-on-the-server-using-aspnet.aspx)

$("#btnSave").click(function () {

    var image = document.getElementById("canvas").toDataURL("image/png");
    image = image.replace('data:image/png;base64,', '');

    $.ajax({
        type: 'POST',
        url: "../../Home/UploadImage?imageData=" + image,
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (msg) {
            alert('Image saved successfully !');
        }
    });
});

the controller:

public 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();
        }
    }
}

But when im trying to convert form base64 the string that is passed like parameter in method, throw an error

Invalid length for a character array Base-64.

like image 621
Fausto Carasai Avatar asked May 29 '12 04:05

Fausto Carasai


1 Answers

You can't post data with querystring parameters

Try this;

    $("#btnSave").click(function () {

        var image = document.getElementById("canvas").toDataURL("image/png");
        image = image.replace('data:image/png;base64,', '');

        $.ajax({
            type: 'POST',
            url: "../../Home/UploadImage",
            data: '{ "imageData" : "' + image + '" }',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function (msg) {
                alert('Image saved successfully !');
            }
        });
    });
like image 90
Mehmet Osmanoglu Avatar answered Oct 19 '22 12:10

Mehmet Osmanoglu