Search code examples
asp.net-coreblazorblazor-webassembly.net-8.0

How to make wwwroot/images part of the web assembly in Blazor auto mode?


I'm using the new .NET 8 Web App template, which creates a primary server project, and a client WASM project.

For the client WASM project, it's working as expected in that when communicating with the server, client side functions are done instantly client side. However, for any images in the wwwroot folder, these are fetched from the server.

Is there any way to make images and assets in wwwroot part of the WASM file(s), so they don't need to be fetched from the server? I realize I can set up image caching, but this seems a band aid fix, and I'd also like it that the full client side app is downloaded in one go, including the images, for a smoother user experience.

How would I go about this? For reference, the wwwroot I'm using for the images is in fact in the .Client WASM project, yet they're still being fetched remotely.


Solution

  • You could try use EmbeddedResource as following sample.
    Assume we have a jpg and txt. (Actually you don't have to put files in wwwroot)
    enter image description here
    Add below to the csproj

        <ItemGroup>
            <EmbeddedResource Include="wwwroot\Assets\test.jpg" />
            <EmbeddedResource Include="wwwroot\Assets\abc.txt" />
        </ItemGroup>
    

    Home.razor

    @page "/"
    @using System.Reflection
    
    <img src="@imagePath">
    <p />
    @txtDisaply
    
    @code
    {
        private string txtDisaply { get; set; }
        private string imagePath { get; set; }
    
        protected override void OnInitialized()
        {
            using var textStream = Assembly.GetExecutingAssembly()
              .GetManifestResourceStream("BlazorApp132.wwwroot.Assets.abc.txt");
            using var tr = new StreamReader(textStream);
            txtDisaply = tr.ReadToEnd();
    
            using var imageStream = Assembly.GetExecutingAssembly()
              .GetManifestResourceStream("BlazorApp132.wwwroot.Assets.test.jpg");
            using var ms = new MemoryStream();
            imageStream.CopyTo(ms);
            var bytes = ms.ToArray();
            imagePath = $"data:img/png;base64,{Convert.ToBase64String(bytes)}";
        }
    }
    

    Test result
    enter image description here