在ASP.NET Core中将画布另存为图像

时间:2019-02-15 15:58:43

标签: javascript asp.net asp.net-core

我正在尝试将javascript画布blob图像发送到ASP.NET Core 2.1中的控制器方法。但我的字符串参数在方法中始终为null

这是我的 JavaScript:

$(".btn").click(function(e) {
    var image = document.getElementById("canvas").toDataURL("image/png");
    image = image.replace('data:image/png;base64,', '');
    $.ajax({
        type: 'POST',
        url: '@Url.Action("Add", "Home")',
        data: { imageData: image },
        ajaxasync: true,
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (msg) {
            alert('Image saved successfully !');
        }
    });
});

这是我的控制器:

[HttpPost]
public  JsonResult Add(string imageData)
{
    try
    {
        var folderName = @"uploads/";
        var webRootPath = _appEnvironment.WebRootPath;
        var newPath = Path.Combine(webRootPath, folderName);
        string fileNameWitPath = newPath + 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();
            }
        }

        return new JsonResult("Success");
        }
    catch (Exception exception)
    {
        return new JsonResult("Error");
    }
}

1 个答案:

答案 0 :(得分:0)

您只需要删除此行

contentType: 'application/json; charset=utf-8'

原因是JQuery默认将以data参数形式传递的对象转换为key1=value1&key2=value2&...格式,这显然是无效的json。因此,您无需指定application/json内容类型,ASP.NET Core将自动正确解析此数据。

但是,如果您想使请求使用json内容类型,则需要执行以下操作

JavaScript

var image = document.getElementById("canvas").toDataURL("image/png");
image = image.replace('data:image/png;base64,', '');
var data = JSON.stringify({ imageData: image }); //serializing object to json

$.ajax({
    type: 'POST',
    url: '@Url.Action("Add", "Home")',
    data: data, //passing json string
    ajaxasync: true,
    contentType: 'application/json',
    dataType: 'json',
    success: function (msg) {
    }
});

C#

public class Model
{
    public string ImageData { get; set; }
}

[HttpPost]
public IActionResult Add([FromBody]Model model) { //..