无法将图像 Base64 字符串从 JavaScript 传递到 Blazor 服务器应用程序中的 C#

时间:2021-02-19 05:41:50

标签: javascript c# blazor-server-side blazor-jsinterop

在我的 Blazor 服务器端应用程序中,我试图将图像 Base64 字符串从 JavaScript(调整大小后)传递到 C#。 在 JavaScript 中,代码位于 FileReader.onload 函数中,因此它不会返回任何内容。
因此,我试图将数据分配给来自 JS 的 HTML textarea 元素,然后在 C# 中从绑定到它的变量中获取它,但这不起作用 - 我得到了空字符串,尽管,我非常确定 textarea 元素具有正确值。
但是,当我用像“Hello from JS”这样的短字符串来模拟返回的字符串时,它会毫无问题地返回。

HTML:
<textarea id="base64ImageTextArea" @bind="base64Image" hidden />

JS:

function ResizeImage(){
        ...
        reader.onload = function (event) {
             ...
             var base64String = ctx.canvas.toDataURL(el.target, item.type, 0); 
             document.getElementById("base64ImageTextArea").value = base64String;
             ...
        }
        ...
}

function GetImageBase64String() {
    return document.getElementById("base64ImageTextArea").value;
}

C#:

private string base64Image;

private async Task OnInputFileChange()
{
    await JSRuntime.InvokeVoidAsync("ResizeImage");
    base64Image = await JSRuntime.InvokeAsync<string>("GetImageBase64String"); // base64Image == ""
}

我还在 Startup.cs 中添加了以下内容:

services.AddServerSideBlazor()
            .AddHubOptions(x => x.MaximumReceiveMessageSize = 102400000);

根本没有异常/错误。

注意:我不想在这一步将图像从 JS 上传到服务器,因为我需要在 C# 中对其进行更多操作。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

因为 FileReader.onload() 是异步运行的并且没有等待,所以我们需要等到它完成它的工作:

private async Task OnInputFileChange()
{
    await JSRuntime.InvokeVoidAsync("ResizeImage");
    while (string.IsNullOrWhiteSpace(base64Image))
    {
         await Task.Delay(100);
         base64Image = await JSRuntime.InvokeAsync<string>("GetImageBase64String");
    }
}

并且不要忘记限制 while 循环。