Saving HTML 5 Canvas as Image on the server using

2020-02-04 10:49发布

问题:

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.

回答1:

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 !');
            }
        });
    });


回答2:

In that example, the author has posted the image data using a hidden field, notice below line of code in his article

<input type="hidden" name="imageData" id="imageData" />

http://www.dotnetfunda.com/articles/show/2665/saving-html-5-canvas-as-image-in-aspnet-mvc

And on click of the button, he is submitting the form after getting canvas data to the hidden field so follow the same approach. As written by Mehmet, querystring has limitations and its prone to be modified as it goes via url.



回答3:

Instead of this

image = image.replace('data:image/png;base64,', '');

use this:

image = image.substr(23, image.length);

remove the leading characters up to the first comma (use any dev tool to see what you posted).