从 iPad 或其他基于触摸的设备发送 Canvas 图像时,我的基于 Canvas 的签名板不会将图像保存到指定目录。尽管在 Visual Studio 和普通 Windows PC 上的实时网站上进行测试时图像数据发送得非常好,但 iPad 似乎无法通过 JavaScript 函数发送 Base64 代码。
在为此站点创建 reprex 时,我注意到在应用程序能够将图像发送到我的本地计算机之前,我需要注释掉 RouteConfig.cs ( thanks to Sanjay Sharma ) 中的一行。从那时起,我尝试查看是否存在任何类型的重定向问题,这些问题会导致在 iPad 上工作时出现问题,但我没有发现任何迹象表明这一点。
此页面作为 ASP.NET Web 窗体站点(Visual C# > Web > 早期版本)构建,包含可与触摸和桌面界面配合使用的 Canvas 。用于制作 Canvas 的代码(在“Drawpad”中调用)基于此处找到的代码:
- https://www.html5canvastutorials.com/labs/html5-canvas-paint-application/
- https://jsfiddle.net/gfcarv/66nVn/
- http://jsfiddle.net/sdncP/
<body data-rsssl="1" onload="DrawPad()">
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<input type="hidden" id="imageData" runat="server" class="image-data" />
<canvas id="myCanvas" width="500" height="100"></canvas>
<br />
<asp:Button ID="btnSave" runat="server" Text="Submit" />
</form>
<script type="text/javascript" id="jsDraw">
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
// function DrawPad() {...} // see the bullet points for this one
$("#btnSave").click(function () {
var image = document.getElementById('myCanvas').toDataURL("image/png");
image = image.replace('data:image/png;base64,', '');
$.ajax({
type: 'POST',
url: 'Default.aspx/UploadImage',
data: '{ imageData : "' + image + '" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json'
});
});
</script>
</body>
然后通过按下按钮(特别是 btnSave)在 C# 文件中调用此函数:
public static void UploadImage(string imageData)
{
using (FileStream fs = new FileStream(@"C:\\Users\\Alex\\Documents\\testpic.png", FileMode.Create))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
bw.Write(Convert.FromBase64String(imageData));
bw.Close();
}
}
}
应用程序应将图像流式传输到预定目录。尽管可以直接访问图像的 Base64 代码,但该过程中的某些内容(无论是 BinaryWriter、FileStream 还是其他内容)导致数据无法写入。因此,在尝试将文件名加载到所需的表中时,尝试签署表单并发送图像会导致基于 SQL 的参数错误;因为文件没有被创建,所以没有文件名,因此无法将数据提交到表中,即使有文件名也没有任何回调。
我最好的猜测是,当从 iPad 提交时,某些原因导致 UploadImage() 方法被完全忽略,但我不知道是什么。
最佳答案
问题实际上不是 JavaScript 错误,而是 C# 错误。这是 UploadImage() 应该做的事情:
public static void UploadImage(string imageData)
{
var impersonator = new ImpersonationHelper("<domain>", "<username>", "<password>");
impersonator.StartImpersonating();
string path = @"\\\\PATH\\TO\\FILE\\DIRECTORY\\";
if (!Directory.Exists(path)) // creates a new folder if this one doesn't currently exist yet
Directory.CreateDirectory(path);
string fileNameWithPath = path + "SIG" + DateTime.Now.ToString("MMddyyyy") + "-" + rand + ".png"; // where rand is randomly-generated elsewhere
byte[] imageBytes = Convert.FromBase64String(imageData);
File.WriteAllBytes(fileNameWithPath, imageBytes);
impersonator.StopImpersonating();
}
代码不应使用 FileWriter,而应将 Base64 字符串拆分为一系列字节,以便无论使用哪个设备发送图像数据,都可以将其写入文件。我已经确认这可以在 iPad 上正常工作,没有任何问题。
关于javascript - 从 iPad 创建 Canvas 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57361515/