file-uploadblazorrazor-componentswwwroot

Blazor - Not able to save file in folder wwwroot/img


I am working on Blazor application and not able to store file in wwwroot/img. Could anyone please help. Wanted to understand the behavior, I am able to see success message(File copied.) on console however not able to see file in folder.

Will try other alternatives but posting it to understand why even after successful execution file not getting stored.

RAZOR COMPONENT

    <InputFile OnChange="HandleFileSelected" />

CODE PART

    private async Task<bool> HandleFileSelected(IFileListEntry[] files)
    {
        try
        {
            IFileListEntry ufile = files.FirstOrDefault();

            if (ufile != null && ufile.Size > 0)
            {
                var fileName = Path.GetFileName(ufile.Name);
                var filePath = @"ProjectPath\wwwroot\img\"+ fileName; //ProjectPath -- path here

                using (var fileStream = new FileStream(filePath, FileMode.Create))
                {
                    await ufile.Data.CopyToAsync(fileStream);
                    Console.WriteLine("File copied.");
                }
                return true;
            }
            return false;
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error "+ ex.Message);
            return false;
        }
    }

CONSOLE MESSAGE

WASM: File copied. //Physically no file copied to path.


Solution

  • Since Blazor WASM is just like any other SPA application. The app is not running on the server but in the clients web browser. This is why the file is not being saved on the server. If you want to save a file to the server you need to communicate with server through something like an API.

    Here is an example on how to upload files using WASM: https://remibou.github.io/Upload-file-with-Blazor/