2

Trying to get things working correctly in Blazor Server Side App. I have an Uploader Component but it doesn't InvokeAsync after each promise is resolved on client side. It waits for all Images to load then Invokes the C# method. How would I get it to Invoke the C# method after each image is loaded?

I know JavaScript is single threaded but also tried with web workers and still does the same thing.

Sample repo can be found here https://dev.azure.com/twinnaz/BlazorUploader

Gif of what's happening.

https://i.stack.imgur.com/7rj7Q.jpg

It should be able to invoke the C# method Async in parallel from javascript file if my thinking is correct.

Wongton
  • 23
  • 3

2 Answers2

3

This issue is related with Blazor and JS. On JS you are not awaiting for GenerateImageData.

You should to use a modern for … ofloop instead, in which await will work as expected:

GetFileInputFiles = async (instance, fileInput) => {
    var files = Array.from(fileInput.files);
    for (const image of files) {
        var imagedata = await readUploadedFileAsText(image);
        console.log("sending");
        _ = await instance.invokeMethodAsync('GenerateImageData', imagedata);
        console.log("sent");
    };
};

On Blazor, I suggest to you to rewrite GenerateImageData as :

    [JSInvokable]
    public async Task GenerateImageData(string data)
    {
        System.Console.WriteLine( "Receiving"  );
        ImageBase64.Add(data);
        await Task.Delay(1);
        StateHasChanged();
        System.Console.WriteLine( "Received"  );
    }

Result:

enter image description here

dani herrera
  • 48,760
  • 8
  • 117
  • 177
  • 1
    Thanks helped a lot !!! Ended up doing it a slightly different way but your knowledge lead to doing more searching and found a better solution to preview the images. I'll update repo with the new code tonight. – Wongton Aug 19 '19 at 00:48
0
GeneratePreviewImages = async (dotNet, fileInput) => {

    const files = Array.from(fileInput.files);

    const imageSrcs = files.map(file => getPreviewImageSrc(file));
    loop(imageSrcs, dotNet);
};



const loop = async (arr, dotNet) => {
    for await (const src of arr) {
        console.log(src);
        dotNet.invokeMethodAsync('GenerateImageData', src);
    }
};

const getPreviewImageSrc = async (file) => {
  return  URL.createObjectURL(file);
};
Wongton
  • 23
  • 3