In Blazor, how does the InputFile component hand selected files to your code, and which default limits do IBrowserFile and InputFileChangeEventArgs enforce?
answer
- OnChange, not @bind-Value
- InputFileChangeEventArgs.File vs GetMultipleFiles
- GetMultipleFiles(maximumFileCount = 10)
- OpenReadStream(maxAllowedSize = 500 KB)
- Size and Name are client-supplied
basics
~10 sInputFile raises OnChange with an InputFileChangeEventArgs; you read IBrowserFile objects from File or GetMultipleFiles and stream each through OpenReadStream. Defaults: 10 files, then GetMultipleFiles throws; 500 KB (512,000 bytes) per stream, then an IOException.
solid answer
~40 s`InputFile` is not an `InputBase<T>` input: it has no `@bind-Value` and no `EditContext` integration, only an `OnChange` callback of type `EventCallback<InputFileChangeEventArgs>`. From the args, `File` returns the single file and throws if none or several were chosen; `GetMultipleFiles(maximumFileCount = 10)` returns them all and throws an `InvalidOperationException` above the count. Each `IBrowserFile` exposes `Name`, `Size`, `ContentType`, `LastModified` and `OpenReadStream(maxAllowedSize = 500 * 1024)`, which throws an `IOException` when the file is larger. Stream it to its destination rather than into a `MemoryStream`, set the limit you really accept, and never trust `Size` or `Name`: the browser supplies them. The component wires its change event through JavaScript interop after first render, so `OnChange` needs an interactive render mode.
code
razor · 23 lines@page "/volunteer/documents"
@rendermode InteractiveServer
@inject IWebHostEnvironment Env
<InputFile OnChange="UploadAsync" multiple accept=".pdf" />
<p>@status</p>
@code {
private const long MaxFileSize = 2 * 1024 * 1024;
private string? status;
private async Task UploadAsync(InputFileChangeEventArgs e)
{
foreach (var file in e.GetMultipleFiles(maximumFileCount: 3))
{
var path = Path.Combine(Env.ContentRootPath, "uploads", Path.GetRandomFileName());
await using var target = File.Create(path);
await using var source = file.OpenReadStream(MaxFileSize);
await source.CopyToAsync(target);
}
status = $"{e.FileCount} file(s) saved.";
}
}go deeper
Recall OnChange with InputFileChangeEventArgs, File versus GetMultipleFiles, and OpenReadStream as the way to read bytes.
Explain the 10-file and 500 KB defaults, the exceptions they throw, and why InputFile needs an interactive render mode for OnChange.
Stream uploads without buffering, set explicit limits, distrust client metadata, and handle static SSR uploads through form mapping.
Decide where large uploads should go, through the circuit or direct to storage from the browser, and the limits each path needs.
## What InputFile is `InputFile` renders an `<input type="file">` and gives .NET code a **stream** for each file the user picks. It is deliberately different from the other input components: - It derives from `ComponentBase`, **not** `InputBase<TValue>`, so there is no `@bind-Value`, no `ValueExpression`, and no automatic `EditContext` validation or CSS classes. - Its only callback is `OnChange`, an `EventCallback<InputFileChangeEventArgs>`, raised when the selection changes. - Extra attributes such as `multiple` and `accept` pass straight through to the element. `accept` only filters the browser's picker; it enforces nothing on the server. - It initializes its browser side through JavaScript interop in `OnAfterRenderAsync(firstRender)`. Under static SSR that never runs, so `OnChange` requires an interactive render mode (Server, WebAssembly or Auto). ## Reading the selection `InputFileChangeEventArgs` offers: | Member | Behaviour | |---|---| | `FileCount` | Number of files chosen | | `File` | The single file; throws `InvalidOperationException` when zero or more than one were chosen | | `GetMultipleFiles(int maximumFileCount = 10)` | All files; throws `InvalidOperationException` ("The maximum number of files accepted is 10, but 12 were supplied.") above the limit | Each file is an **`IBrowserFile`** with `Name`, `Size`, `ContentType`, `LastModified`, `OpenReadStream(long maxAllowedSize = 500 * 1024, CancellationToken)` and, through an extension, `RequestImageFileAsync(format, maxWidth, maxHeight)` for a resized image. ## The 500 KB default and why it exists `OpenReadStream` enforces a maximum stream size. The default, 500 KB (512,000 bytes), is low on purpose: it stops a developer from accidentally reading a large file into server memory. Larger files make it throw an `IOException`. Pass the size you actually accept: 1. Decide a limit per use, for example 2 MB for a volunteer's ID scan. 2. Call `file.OpenReadStream(maxAllowedSize: limit, cancellationToken)`. 3. Copy the stream to its destination with `CopyToAsync`, a file or blob client, rather than buffering it whole. On Interactive Server the bytes travel from the browser over the circuit as they are read; on WebAssembly they are read inside the browser and then usually sent to an API. Copying everything into a `MemoryStream` first multiplies memory use per upload and invites denial of service on a server-rendered app. ## Do not trust the metadata `Name`, `Size`, `ContentType` and `LastModified` are what the browser reports. Use them for preliminary checks and display only: - Enforce size with `maxAllowedSize`, not with `if (file.Size < ...)`. - Never use `Name` as a storage path; generate a file name such as `Path.GetRandomFileName()`. - Encode the name before showing it back to the user. - Validate content type and content on the server if it matters. ## Files in a static SSR form A statically rendered form cannot use `OnChange`, but it can still upload: the browser posts the file in a `multipart/form-data` body, and Blazor's form mapper can bind a `[SupplyParameterFromForm]` property of type `IBrowserFile`, `IFormFile` or a list of either. The mapped `IBrowserFile` applies the same 512,000-byte default in `OpenReadStream`. ## Cancellation and progress Long uploads need two more pieces of plumbing: - Pass a `CancellationToken` to `OpenReadStream` and to `CopyToAsync`, from a `CancellationTokenSource` a cancel button can trigger, so an abandoned upload stops reading. - For a progress bar, copy in a loop with a fixed buffer, add each chunk's length to a running total, and call `StateHasChanged()` every so often instead of after every chunk. - Read files one after another. Opening streams for several files at once and reading them later is a known cause of `TimeoutException` in server-side uploads. - On Interactive Server, remember that every byte crosses the circuit; very large files are often better sent by the browser directly to storage. ## Validation Because `InputFile` does not join the `EditContext`, a rule such as "a document is required" is yours to enforce: keep the selected `IBrowserFile` in a model property and validate that property, or add a message to a `ValidationMessageStore` from the `OnChange` handler.
- Why is checking file.Size before calling OpenReadStream not a safe size limit?`Size` is reported by the browser, so a crafted client can lie about it. `OpenReadStream(maxAllowedSize)` counts the bytes actually supplied and throws an `IOException` past the limit, so the enforced limit belongs there; `Size` is fine only for an early friendly message.
- A user selects one file but the handler reads e.File inside a multiple input and later twelve files arrive; what breaks?`File` throws an `InvalidOperationException` when more than one file was supplied, and `GetMultipleFiles()` with its default of 10 also throws for twelve. Use `GetMultipleFiles(maximumFileCount: n)` with the count you accept and show a message when the selection is larger.
- InputFile supports @bind-Value and validates through the EditContext like InputText.
- OpenReadStream has no default limit and reads any file size.
- Checking IBrowserFile.Size is enough to enforce a maximum upload size.
- Using the browser-supplied file Name as the storage path is fine.
- InputFile's OnChange fires in a statically rendered component.