In a Blazor WebAssembly application, I needed to export data to a file. In a web application you cannot write the file directly to the file system. Instead, you need to create a valid URL, create a <a>
element, and trigger a click on it. There are 2 ways to create a valid URL:
data:text/plain;base64,SGVsbG8sIFdvcmxkIQ==
), but there are a few limitations included a limited file size (Common problems)URL.createObjectURL(blob)
So, the best solution is to create a Blob
, so there is no limitation in size. Using WebAssembly this is also much faster!
Let’s create the razor page with 2 buttons to generate a file and download it:
@page "/"
@inject IJSRuntime JSRuntime
<button @onclick="DownloadBinary">Download binary file</button>
<button @onclick="DownloadText">Download text file</button>
@code{
async Task DownloadBinary()
{
// Generate a file
byte[] file = Enumerable.Range(0, 100).Cast<byte>().ToArray();
// Send the data to JS to actually download the file
await JSRuntime.InvokeVoidAsync("BlazorDownloadFile", "file.bin", "application/octet-stream", file);
}
async Task DownloadText()
{
// Generate a text file
byte[] file = System.Text.Encoding.UTF8.GetBytes("Hello world!");
await JSRuntime.InvokeVoidAsync("BlazorDownloadFile", "file.txt", "text/plain", file);
}
}
#blazor #.net #asp.net core #webassembly