First problem:
Looking at your code, the
html2canvas
function returns a
Promise[
^].
The callback function passed to
then
won't be invoked immediately; it will be invoked when the function has completed.
Therefore, when you go to post the data, the
base64
variable will be blank, and you will be sending an empty string to your controller.
To solve that, you need to move the remainder of your function to the callback:
$("#btnExportAsImageByPost").click(function () {
html2canvas($("#Table")[0]).then(function (canvas) {
var base64 = canvas.toDataURL();
document.body.appendChild(canvas);
alert(base64);
$("[id*=hfImageData]").val(base64);
var url = "/HtmlToImage/Index/";
$.ajax({
...
});
});
});
Second problem:
As pointed out in Solution 1, you need to post an object with the correct parameter name:
$.ajax({
type: 'POST',
url: url,
data: { base64: base64 },
dataType: "string",
success: function (evt) {
$("#Table").hide('slow');
}
});
Third problem:
The string returned from
the canvas.toDataURL()
method[
^] will be
a data URI[
^] - something that looks like:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAADElEQVQImWNgoBMAAABpAAFEI8ARAAAAAElFTkSuQmCC
If you try to pass that string to
Convert.FromBase64String
, you will get an exception, because it is not a valid Base64-encoded string.
You need to remove the
data:image/png;base64,
prefix from the start of the string first.
[HttpPost]
[ActionName("Index")]
public ActionResult Index_Post(string base64)
{
int index = base64.IndexOf(',');
if (index != -1) base64 = base64.Substring(index + 1);
byte[] bytes = Convert.FromBase64String(base64);
return File(bytes, "image/png", "HtmlToImage.png");
}