How to Download a File in Blazor (Stream, URL, Endpoint and CSV)

If you need a Blazor download file button, wrap your .NET Stream in a DotNetStreamReference and pass it to a small JavaScript function that turns the bytes into a Blob and clicks a temporary link:

using var streamRef = new DotNetStreamReference(stream: fileStream);
await JS.InvokeVoidAsync("downloadFileFromStream", "invoice-1042.pdf", streamRef);

Blazor has no built-in download API, so that’s where most people get stuck. I ran this pattern and three others on .NET 10 and checked every file the browser really saved.

The Sample Blazor App We’ll Use

The running sample is a downloads page for Bayside Outfitters, a made-up outdoor store in San Diego, California. It’s a Blazor Web App with the InteractiveServer render mode on .NET SDK 10.0.402 (check your .NET version first).

New to Blazor? My Blazor tutorial for beginners walks through the template. Here’s what the page offers:

  • invoice-1042.pdf (625 bytes), kept in a private Files folder outside wwwroot
  • return-policy-2026.txt (223 bytes), a public file in wwwroot/files
  • orders-2026-11.csv, four US orders built in memory (177 bytes)

The private invoice is the tricky one: the browser can’t reach it by URL, so C# has to send the bytes.

dotnet new blazor -o W13BlazorDownload

I deleted appsettings.Development.json, trimmed Program.cs to plain http and set port 5911. Here are the four files as they ran:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}
{
  "$schema": "https://json.schemastore.org/launchsettings.json",
  "profiles": {
    "http": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": false,
      "applicationUrl": "http://localhost:5911",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}
<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <BlazorDisableThrowNavigationException>true</BlazorDisableThrowNavigationException>
  </PropertyGroup>

</Project>
using W13BlazorDownload;
using W13BlazorDownload.Components;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorComponents()
    .AddInteractiveServerComponents();

var app = builder.Build();
app.UseAntiforgery();
app.MapStaticAssets();
app.MapDownloadEndpoints();          // Method 3 + the CSV endpoint
app.MapRazorComponents<App>()
    .AddInteractiveServerRenderMode();
app.Run();

The page is Components/Pages/Downloads.razor. Every method below points back at one of its three buttons:

@page "/downloads"
@rendermode InteractiveServer
@inject IJSRuntime JS
@inject IWebHostEnvironment Env

<PageTitle>Downloads</PageTitle>

<h1>Bayside Outfitters - Downloads</h1>
<p>Order #1042 for Tyler Brooks, San Diego, CA</p>

<button id="invoice" class="btn btn-primary" @onclick="DownloadInvoice">Invoice PDF (stream)</button>
<button id="policy" class="btn btn-outline-primary" @onclick="DownloadPolicy">Return policy (URL)</button>
<button id="csv" class="btn btn-success" @onclick="ExportCsv">Export orders CSV</button>

<ul class="mt-3">
    @foreach (var line in log)
    {
        <li>@line</li>
    }
</ul>

@code {
    private readonly List<string> log = [];

    // Method 1: stream a file from the server's private Files folder
    private async Task DownloadInvoice()
    {
        var path = Path.Combine(Env.ContentRootPath, "Files", "invoice-1042.pdf");
        var fileStream = File.OpenRead(path);
        var size = fileStream.Length;

        using var streamRef = new DotNetStreamReference(stream: fileStream);
        await JS.InvokeVoidAsync("downloadFileFromStream", "invoice-1042.pdf", streamRef);
        log.Add($"Streamed invoice-1042.pdf ({size} bytes)");
    }

    // Method 2: let the browser fetch a public file by URL
    private async Task DownloadPolicy()
    {
        await JS.InvokeVoidAsync("triggerFileDownload",
            "return-policy-2026.txt", "/files/return-policy-2026.txt");
        log.Add("Sent the browser to /files/return-policy-2026.txt");
    }

    // Method 4: build a CSV in memory and stream it
    private async Task ExportCsv()
    {
        byte[] csv = OrderCsv.Build();
        using var streamRef = new DotNetStreamReference(new MemoryStream(csv));
        await JS.InvokeVoidAsync("downloadFileFromStream", "orders-2026-11.csv", streamRef);
        log.Add($"Exported {OrderCsv.Orders.Length} orders ({csv.Length} bytes)");
    }
}

I clicked all three buttons in headless Edge with its download folder set to BrowserDownloads\interactive:

Blazor download file demo page in Edge with Invoice PDF, Return policy and Export orders CSV buttons and a log showing 625 bytes streamed and 4 orders exported
The Bayside Outfitters downloads page after all three buttons were clicked

Method 1: Stream a File to the Browser With DotNetStreamReference (Recommended)

Use this when your file is under about 250 MB and your users can’t fetch it by URL, like a private invoice. Same Bayside app: the first button streams invoice-1042.pdf from the server’s Files folder.

First, the JavaScript. I put Microsoft’s two helper functions in wwwroot/js/file-download.js:

window.downloadFileFromStream = async (fileName, contentStreamReference) => {
  const arrayBuffer = await contentStreamReference.arrayBuffer();
  const blob = new Blob([arrayBuffer]);
  const url = URL.createObjectURL(blob);
  const anchorElement = document.createElement('a');
  anchorElement.href = url;
  anchorElement.download = fileName ?? '';
  anchorElement.click();
  anchorElement.remove();
  URL.revokeObjectURL(url);
}

window.triggerFileDownload = (fileName, url) => {
  const anchorElement = document.createElement('a');
  anchorElement.href = url;
  anchorElement.download = fileName ?? '';
  anchorElement.click();
  anchorElement.remove();
}

Then App.razor loads that file right after the Blazor script:

<body>
    <Routes />
    <ReconnectModal />
    <script src="@Assets["_framework/blazor.web.js"]"></script>
    <script src="@Assets["js/file-download.js"]"></script>
</body>

The C# side is DownloadInvoice in the page above. Edge reported a download from a blob URL, and the saved file matched the original byte for byte:

[download] begin invoice-1042.pdf from blob: object URL
[download] completed invoice-1042.pdf 625 bytes
Comparing files FILES\invoice-1042.pdf and BROWSERDOWNLOADS\INTERACTIVE\INVOICE-1042.PDF
FC: no differences encountered

invoice-1042.pdf  625 bytes
orders-2026-11.csv  177 bytes
return-policy-2026.txt  223 bytes
VS Code with file-download.js open and the terminal showing fc reporting no differences between the server invoice and the downloaded invoice-1042.pdf, plus the three downloaded files with their sizes
file-download.js next to the fc check of the downloaded invoice

How does this code work?

DotNetStreamReference tells Blazor to send the bytes over its native byte-streaming interop instead of serializing them to JSON. On the JS side, arrayBuffer() reads the whole stream into browser memory.

The function wraps that buffer in a Blob, makes an object URL, and clicks an anchor whose download attribute carries the file name. The await matters (async and await in C# explains why): the call returns once the browser has the bytes.

The constructor is DotNetStreamReference(Stream stream, bool leaveOpen = false), so you don’t close the file stream yourself; Blazor does it after the transfer. That’s why I read fileStream.Length before the call, not after.

Important: keep URL.revokeObjectURL(url). Microsoft calls it the step that stops memory leaking on the client, the browser-side cousin of the Dispose pattern in C#.

Method 2: Download a File From a URL With triggerFileDownload

Use this when your file already sits at a URL your users can reach, and for anything 250 MB or bigger. Nothing streams through the circuit; the browser fetches the file itself.

Same Bayside app, second button. The public file is wwwroot/files/return-policy-2026.txt:

Bayside Outfitters - Return Policy (2026)
Unworn items can be returned within 30 days with the receipt.
Refunds go back to the original card in 5-7 business days.
Questions? Call (619) 555-0148, Mon-Fri 9 AM - 5 PM PT.

DownloadPolicy hands the name and the relative URL to triggerFileDownload from Method 1’s JS file. Edge saved all 223 bytes straight from the server:

[download] begin return-policy-2026.txt from http://localhost:5911/files/return-policy-2026.txt
[download] completed return-policy-2026.txt 223 bytes

How does this code work?

It’s the same anchor trick without the Blob. Static files don’t send a Content-Disposition header, so the download attribute is what turns this request into a save:

HTTP/1.1 200 OK
Content-Length: 223
Content-Type: text/plain
Accept-Ranges: bytes

So here’s the catch: browsers only honor download for same-origin URLs. I called the same function with http://127.0.0.1:5911/..., a different origin than localhost:5911.

Nothing was saved. Edge simply opened the text file, and the tab ended up on http://127.0.0.1:5911/files/return-policy-2026.txt showing the policy text. For files on a CDN or another API, set up CORS in ASP.NET Core or serve a Content-Disposition header.

Method 3: Download a File From a Minimal API Endpoint With Results.File

Use this when you serve big files, files behind a permission check, or pages that aren’t interactive. A plain link works in every render mode because no JavaScript or circuit is involved.

Same Bayside app, same invoice. I put two endpoints in DownloadEndpoints.cs and mapped them with one line in Program.cs:

namespace W13BlazorDownload;

public static class DownloadEndpoints
{
    public static void MapDownloadEndpoints(this WebApplication app)
    {
        var folder = Path.Combine(app.Environment.ContentRootPath, "Files");

        app.MapGet("/files/invoice/{id:int}", (int id) =>
        {
            var path = Path.Combine(folder, $"invoice-{id}.pdf");
            return File.Exists(path)
                ? Results.File(path, "application/pdf", $"invoice-{id}.pdf")
                : Results.NotFound();
        });

        app.MapGet("/reports/orders.csv", () =>
            Results.File(OrderCsv.Build(), "text/csv", "orders-2026-11.csv"));
    }
}

The static SSR page Components/Pages/Reports.razor has no @rendermode, just two links:

@page "/reports"

<PageTitle>Reports</PageTitle>

<h1>Bayside Outfitters - Reports</h1>
<p>Static SSR page: no circuit, no JavaScript interop, just links.</p>

<ul>
    <li><a id="orders-link" href="/reports/orders.csv" download>November 2026 orders (CSV)</a></li>
    <li><a id="invoice-link" href="/files/invoice/1042" download>Invoice #1042 (PDF)</a></li>
</ul>
Static SSR Blazor Reports page with two download links: November 2026 orders CSV and Invoice 1042 PDF
The static SSR Reports page: plain links, no circuit

Clicking both links in Edge saved orders-2026-11.csv and invoice-1042.pdf. curl shows the header that makes it work, and the 404 for an invoice that doesn’t exist:

HTTP/1.1 200 OK
Content-Length: 625
Content-Type: application/pdf
Date: Sun, 08 Nov 2026 02:49:42 GMT
Server: Kestrel
Last-Modified: Sun, 08 Nov 2026 02:49:33 GMT
Content-Disposition: attachment; filename=invoice-1042.pdf; filename*=UTF-8''invoice-1042.pdf

invoice 9999: 404
VS Code with DownloadEndpoints.cs open and the terminal showing curl output with Content-Type application/pdf, Content-Disposition attachment filename invoice-1042.pdf and a 404 for invoice 9999
Results.File sends Content-Disposition: attachment with the file name

How does this code work?

Results.File takes the path, the content type and fileDownloadName. The name becomes Content-Disposition: attachment, which tells any browser to save the response instead of showing it.

The {id:int} constraint and the fixed invoice-{id}.pdf pattern mean nobody can ask for ../appsettings.json. Kestrel streams the file from disk, so a 2 GB file never sits in memory.

What happens without download on the link? I added one to the Reports page. Blazor’s enhanced navigation grabbed the click first and logged:

Enhanced navigation failed for destination http://localhost:5911/reports/orders.csv. Falling back to full page load.

The full page load still saved the CSV, thanks to the header. Keep download on file links anyway: it skips that wasted fetch. This is the minimal API style; a controller’s File() works the same way.

Pro Tip: pass enableRangeProcessing: true for large files so browsers can resume a broken download. Watch the overloads: for byte[] it’s the 4th parameter, for a path or Stream it’s the last.

Method 4: Generate a CSV File on the Fly and Download It in Blazor

Use this when you need an export: a report, a filtered grid, an order history. Your file never touches disk. Same Bayside orders: four sales from California, Texas, Colorado and Oregon.

Here’s OrderCsv.cs, built with a StringBuilder and a record for each order:

using System.Globalization;
using System.Text;

namespace W13BlazorDownload;

public record Order(int Id, string Customer, string City, string State, decimal Total);

public static class OrderCsv
{
    public static readonly Order[] Orders =
    [
        new(1042, "Tyler Brooks", "San Diego", "CA", 184.50m),
        new(1043, "Jenna Morales", "Austin", "TX", 92.00m),
        new(1044, "Marcus Reed", "Denver", "CO", 1249.99m),
        new(1045, "Olivia Chen", "Portland", "OR", 37.25m),
    ];

    public static byte[] Build()
    {
        var sb = new StringBuilder("OrderId,Customer,City,State,Total\n");
        foreach (var o in Orders)
            sb.Append(CultureInfo.InvariantCulture,
                $"{o.Id},{o.Customer},{o.City},{o.State},{o.Total:F2}\n");
        return Encoding.UTF8.GetBytes(sb.ToString());
    }
}

The third button calls ExportCsv: OrderCsv.Build(), a MemoryStream, and the same downloadFileFromStream function as Method 1. Edge saved 177 bytes, and the file opened like this:

OrderId,Customer,City,State,Total
1042,Tyler Brooks,San Diego,CA,184.50
1043,Jenna Morales,Austin,TX,92.00
1044,Marcus Reed,Denver,CO,1249.99
1045,Olivia Chen,Portland,OR,37.25
VS Code with OrderCsv.cs open and the terminal printing the downloaded orders-2026-11.csv: a header row and four US orders from San Diego, Austin, Denver and Portland
OrderCsv.cs next to the CSV file the browser saved

How does this code work?

CultureInfo.InvariantCulture keeps the decimal point a period on every server, so 1249.99 doesn’t come out as 1249,99 on a German machine. F2 gives every total two decimals.

Encoding.UTF8.GetBytes turns the text into the bytes the stream carries. The /reports/orders.csv endpoint from Method 3 returns the exact same 177 bytes, so a static page can export too.

Important: this sample has no commas or quotes inside values. Your real data will, so wrap those fields in double quotes (and double any quote inside) or use a CSV library.

Does Blazor File Download Work in Every Render Mode?

Not every method. Methods 1, 2 and 4 call JavaScript from a button’s @onclick, so your component needs an interactive render mode. My Blazor render modes guide explains the options.

Render modeStream (1, 4)URL via JS (2)Endpoint link (3)
Static SSRNoOnly with your own addEventListenerYes
InteractiveServerYesYesYes
InteractiveWebAssemblyYesYesYes
InteractiveAutoYesYesYes

On Blazor Server the bytes travel over the SignalR circuit, so a huge stream ties it up. Going the other way? See my guide to uploading files to an ASP.NET Core Web API.

Which Blazor Download File Method Should You Use?

SituationUse
Private file under ~250 MB, interactive pageMethod 1: DotNetStreamReference
Public file in wwwroot, same originMethod 2: triggerFileDownload
Large file, auth check, or static SSR pageMethod 3: Results.File + <a download>
Export generated in C#Method 4: MemoryStream + Method 1

If you’re unsure, build the endpoint first; it works everywhere. Files in Azure Blob Storage fit that path too: stream the blob from the endpoint.

Things to Keep in Mind

  • The stream approach loads the whole file into browser memory. Past ~250 MB, switch to a URL or an endpoint.
  • Always call URL.revokeObjectURL after the click, or every download leaks a Blob.
  • The download attribute is ignored for cross-origin URLs; send Content-Disposition: attachment from the server instead.
  • Never build a file path from raw user input. Map an ID to a known folder, like the {id:int} route here.
  • JS interop doesn’t run on static SSR pages. Use an endpoint link there.

Once downloads work, these Bayside follow-ups pair well with them:

Frequently Asked Questions

How do I download a file in Blazor?

Wrap a Stream in DotNetStreamReference and call a JavaScript function such as downloadFileFromStream with JS.InvokeVoidAsync. The function reads the stream into an ArrayBuffer, creates a Blob and an object URL, and clicks an anchor with the download attribute.

How do I download a file from a URL in Blazor?

Create an anchor element in JavaScript, set href to the URL and download to the file name, then call click(). This works for same-origin URLs; for another origin the browser ignores the download attribute, so configure CORS or send Content-Disposition.

What is the file size limit for Blazor file downloads?

There’s no hard limit, but Microsoft recommends the stream approach for files under 250 MB because the whole file lands in browser memory. For 250 MB or more, download from a URL or a server endpoint.

Can I download a file in Blazor without JavaScript?

Yes. Map an endpoint that returns Results.File(path, contentType, fileDownloadName) and link to it with an a tag that has the download attribute. It works on static SSR pages too.

How do I set the downloaded file name in Blazor?

With JS interop, the anchor’s download attribute sets it. From an endpoint, pass fileDownloadName to Results.File, which sends Content-Disposition: attachment. Microsoft Learn’s ASP.NET Core Blazor file downloads page covers both.