How do I generate and save a file client-side using Blazor?

Platform: Blazor| Category: General

Since there is no built-in functionality for saving files in Blazor, it is necessary to write the function in JavaScript and then invoke the JavaScript function from C# code in Blazor. In this solution, we have used JavaScript interop for file saving and generation in client-side Blazor.

  1. Create a new JavaScript file, saveFile.js, in the wwwroot folder and add the following code.
    [saveFile.js]

    function saveFile(file, Content) {
    var link = document.createElement('a');
    link.download = name;
    link.href = "data:text/plain;charset=utf-8," + encodeURIComponent(Content)
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    }

  2. Reference the new script file in the index.html page as shown.
    [index.html]

    <body>
        ………………………… . .
        <script src="_framework/blazor.webassembly.js"></script>
        <script src="saveFile.js"></script>
    </body>

  3. Invoke the JavaScript function in a new Razor page.
    [Savefile.razor]

    page "/savefile"
     
    @inject IJSRuntime JSRuntime
     
    <h1>Blazor Save & Generate File</h1><textarea @bind="fileContent"
    style="width:150px;height:100px" />
     
    <button @onclick="SaveFile">SaveFile</button>
     
    <button @onclick="DownloadFile">GenerateFile</button>
     
    @code {
     
        string Content;
     
        string fileContent;
     
        string fileName = "file.txt";
     
        public  void SaveFile()
        {
           Content = fileContent;
        }
        public async void DownloadFile()
        {
            await JSRuntime.InvokeAsync<object>("saveFile",fileName,Content);
       }
    }

  4. Run the app. Save and generate the file in text format.

    View Sample in GitHub

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.