0

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.

Nithin B
  • 601
  • 1
  • 9
  • 26

1 Answers1

1

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

Community
  • 1
  • 1
xszaboj
  • 1,035
  • 7
  • 21