简体   繁体   中英

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.

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.

So the reason why you are receiving null on controller is because the then function is not finished by that time. And base64 string is null. If you want to know more try to read something more about how asynchronous javascript work or how promises work ;).

Have a look on this thread: html2canvas javascript screenshot and upload

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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