2

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.

ZKS
  • 817
  • 3
  • 16
  • 31
  • You don't have a filesystem like that in a WASM client - it is running in the browser, not on the server. Did you intend to save it somewhere on the Browser? If so, get the data and store it in LocalStorage. If you wanted to send it to a server, you will need an API on the server and then POST the file to that api. – Mister Magoo Apr 03 '20 at 11:06

1 Answers1

3

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/

ZarX
  • 1,096
  • 9
  • 17
  • Thanks Mister Magoo and ZarX I am clear now...will implement an api to achieve the result. Got confused with asp.net and wasm.. – ZKS Apr 03 '20 at 11:35
  • 1
    I have question regarding same, I am able to make call to api and store the file on server. What are the ways possible to reference this file back in my component?? Also I have seen examples where client project itself is having controller which is storing file to wwwroot/img folder so that it accessible to be rendered on component. Wanted to understand what is correct approach. I am working on the blog application and want to store images link along with text. I believe that controllers should always be on server which is by default structured with the Blazor project template. – ZKS Apr 04 '20 at 19:17