[英]Save canvas as image in ASP.NET Core
I'm trying to send a javascript canvas blob image to my controller method in ASP.NET Core 2.1. 我正在尝试将javascript画布blob图像发送到ASP.NET Core 2.1中的控制器方法。 but my string parameters is always
null
in method. 但我的字符串参数在方法中始终为
null
。
This is my JavaScript: 这是我的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 !');
}
});
});
This is my Controller: 这是我的控制器:
[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");
}
}
You just need to remove this line 您只需要删除此行
contentType: 'application/json; charset=utf-8'
The reason is JQuery transforms object passed as data
param to key1=value1&key2=value2&...
format by default which apparently is not valid json. 原因是JQuery默认将作为
data
参数传递的对象转换为key1=value1&key2=value2&...
格式,这显然是无效的json。 So you do not need to specify application/json
content type and ASP.NET Core will automatically parse this data properly. 因此,您无需指定
application/json
内容类型,ASP.NET Core将自动正确解析此数据。
But if you want to make the request work with json
content type you will need to do the following 但是,如果要使请求与
json
内容类型一起使用,则需要执行以下操作
JavaScript 的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# C#
public class Model
{
public string ImageData { get; set; }
}
[HttpPost]
public IActionResult Add([FromBody]Model model) { //..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.