简体   繁体   English

如何从MVC中的控制器下载由html2canvas创建的字节形式的图像(在浏览器中显示保存对话框)?

[英]How to download image(show save dialog in browser) that is in the form of bytes created by html2canvas from controller in MVC?

I am trying to send image created by image2canvas to controller using ajax and then download it using controller. 我正在尝试使用Ajax将image2canvas创建的图像发送到控制器,然后使用控制器下载它。

Here is my code: 这是我的代码:

$("#btnExportAsImageByPost").click(function () {
        var base64;
        html2canvas($("#Table")[0]).then(function (canvas) {
            base64 = canvas.toDataURL();
            document.body.appendChild(canvas);
            alert(base64);
            $("[id*=hfImageData]").val(base64);
        });
        alert(base64);
        var url = "/HtmlToImage/Index/";
        $.ajax({
            type: 'POST',
            url: url,
            data: base64,
            dataType: "string",
            success: function (evt) {
                $("#Table").hide('slow');
            },
        });
    });


<div id="Table" style="width:340px;background-color:White;padding:5px">
<table cellspacing="0" rules="all" border="1" style="border-collapse: collapse;">
    <tr>
        <th scope="col" style="width: 90px;">Customer id</th>
        <th scope="col" style="width: 120px;">Name</th>
        <th scope="col" style="width: 120px;">Country</th>
    </tr>
    <tr>
        <td>1</td>
        <td>John Hammond</td>
        <td>United States</td>
    </tr>
    <tr>
        <td>2</td>
        <td>Mudassar Khan</td>
        <td>India</td>
    </tr>
</table>

Here is my controller action: 这是我的控制器动作:

[HttpPost]
        [ActionName("Index")]
        public ActionResult Index_Post(string base64)
        {
            byte[] bytes = Convert.FromBase64String(base64);
            return File(bytes, "image/png", "HtmlToImage.png");
        }

But problem is nothing happens in browser when the controller returns file. 但是问题是当控制器返回文件时,在浏览器中什么也没有发生。 Instead of prompting to save file. 而不提示您保存文件。

I think you problem is that then function is going to be asynchronous promise. 我认为您的问题是函数将成为异步诺言。 So you have to call the ajax inside that. 因此,您必须在其中调用ajax。

So the reason why you are receiving null on controller is because the then function is not finished by that time. 因此,您在控制器上收到null的原因是,那时功能尚未完成。 And base64 string is null. 并且base64字符串为null。 If you want to know more try to read something more about how asynchronous javascript work or how promises work ;). 如果您想了解更多信息,请尝试阅读有关异步javascript如何工作或promises如何工作的更多信息;)。

Have a look on this thread: html2canvas javascript screenshot and upload 看看这个线程: html2canvas javascript截图和上传

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM