简体   繁体   中英

Cannot pass image Base64 string from JavaScript to C# in Blazor server app

In my Blazor server side app I'm trying to pass an image Base64 string from JavaScript (after resizing) to C#. In JavaScript the code is in the FileReader.onload func, so it won't return anything.
Therefore, I'm trying to assign the data to an HTML textarea element from JS, and then pick it up from bound to it variable in C#, but this doesn't work - I'm getting empty string, although, I'm pretty sure the textarea element has a correct value.
But, when I mock the returning string with short one like "Hello from JS", it gets returned without any problems.

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 == ""
}

I've also added the following to Startup.cs:

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

No exceptions/errors at all.

Note: I don't wanna upload the image to the server from JS at this step as I need to do some more manipulations on it in C#.

Any ideas?

Because the FileReader.onload() runs asynchronously and is not awaited, we need to wait until it is finished it's job:

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

And don't forget to limit while loops.

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