How to Download a File from a Secure Web API in Blazor WebAssembly

In this article, we will walk through how to download a file from an authenticated Web API endpoint in a Blazor WebAssembly app. The API returns a CSV file, and we will securely download it using JavaScript interop.

1. Web API Endpoint

Our API controller action returns a CSV file and requires authentication:

[HttpGet("export/template")]
[Authorize]
public async Task<IActionResult> GetTemplate(CancellationToken cancellationToken)
{
byte[] fileBytes = GetTemplateCsvBytes();
return File(fileBytes, "text/csv", "template.csv");
}

2. Blazor Web Assembly

We create a method to call the API and get the file bytes. We then use JavaScript interop to trigger the download.

@inject HttpClient HttpClient
@inject IJSRuntime JSRuntime
<button @onclick="DownloadTemplate">Download</button>
private async Task DownloadTemplate()
{
HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "<access_token>");
var response = await HttpClient.GetAsync(url);
response.EnsureSuccessStatusCode();
var fileBytes = await response.Content.ReadAsByteArrayAsync();
var fileName = $"template.csv";
await JSRuntime.InvokeVoidAsync("downloadFileFromBytes", fileName, fileBytes);
}

Blazor now handles byte arrays more efficiently by skipping the Base64 conversion.

Then we call the JavaScript function: downloadFileFromBytes() to send the file name and data from the C# code to JavaScript, so the browser can download it.

3. JavaScript Interop

Add this JavaScript function to wwwroot/index.html (or a separate JS file):

function downloadFileFromBytes(fileName, fileBytes) {
const blob = new Blob([fileBytes]);
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = fileName;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
}

This JavaScript function downloads a file in the browser. It takes a file name and bytes data from C# code in Blazor then creates a temporary link to download it.

Thank you for reading 👍

Learn more How to Download a File from a Secure Web API in Blazor WebAssembly

Leave a Reply