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.
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);
}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>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);
}
}Run the app. Save and generate the file in text format.
View Sample in GitHub
Share with