我正在使用html2canvas库从页面获取快照,以及如何在C#Controller中获取该图像?
查看
$("#button").click(function () {
var image;
html2canvas(document.body, {
onrendered: function (canvas) {
image = convertCanvasToImage(canvas);
$.post("../../HomeController/SetScreenShot", {
sendImage: image
}, function () {});
}
});
});
CONTROLLER
public void SetScreenShot()
{
HttpPostedFileBase file = new HttpPostedFileBase();
file = Request.Form["sendImage"].ToString();
}
答案 0 :(得分:2)
简单地说,可以跳过隐藏的输入。这样就可以了:
$("#button").click(function () {
html2canvas(document.body, {
onrendered: function(canvas) {
var image = canvas.toDataURL("image/png");
image = image.replace('data:image/png;base64,', '');
$.ajax({
type: "POST",
url: '../../HomeController/SaveSnapshot',
dataType: 'text',
data: { base64data : image },
success: function(result) { alert(result); }
});
}
});
CONTROLLER (修改后的版本,将图片保存到映射文件夹):
[HttpPost]
public ActionResult SaveSnapshot()
{
bool saved = false;
if (Request.Form["base64data"] != null) {
string image = Request.Form["base64data"].ToString();
byte[] data = Convert.FromBase64String(image);
var path = Path.Combine(Server.MapPath("~/Upload"), "snapshot.png");
System.IO.File.WriteAllBytes(path, data);
saved = true;
}
return Json(saved ? "image saved" : "image not saved");
}
答案 1 :(得分:1)
我找到了怎么做,只需要将该图像附加到页面上的隐藏输入中,然后从图像src发送它
查看强>
<input type="hidden" id="hiddenScreen" />
<script>
function convertCanvasToImage(canvas) {
var image = new Image();
image.src = canvas.toDataURL("image/png");
image.id = "canvasimage";
return image;
}
$("#button").click(function () {
var image;
var data;
html2canvas(document.body, {
onrendered: function(canvas) {
image = convertCanvasToImage(canvas);
$("#hiddenScreen").append(image);
data = $('#canvasimage').attr('src');
}
});
$.ajax({
type: "POST",
url: '../../HomeController/SetScreenShot',
dataType: 'text',
data: {
base64data : data
}
});
</script>
<强> CONTROLLER 强>
public void SetScreenShot()
{
if (Session["screenShot"] == null) Session.Add("screenShot", "");
Session["screenShot"] = Request.Form["base64data"].ToString();
}