Creator of Blazor Steve Sanderson used JavaScript interop for similar task during one of his last presentations.
You can find example on BlazorExcelSpreadsheet
Solution includes three parts:
1) JavaScript
function saveAsFile(filename, bytesBase64) {
var link = document.createElement('a');
link.download = filename;
link.href = "https://stackoverflow.com/questions/52683706/data:application/octet-stream;base64," + bytesBase64;
document.body.appendChild(link); // Needed for Firefox
link.click();
document.body.removeChild(link);
}
2) C# interop wrapper
public static class FileUtil
{
public async static Task SaveAs(IJSRuntime js, string filename, byte[] data)
{
await js.InvokeAsync<object>(
"saveAsFile",
filename,
Convert.ToBase64String(data));
}
}
3) Call from your component
@inject IJSRuntime js
@functions {
void DownloadFile() {
var text = "Hello, world!";
var bytes = System.Text.Encoding.UTF8.GetBytes(text);
FileUtil.SaveAs(js, "HelloWorld.txt", bytes);
}
}
You can see it an action in Blazor Fiddle