Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 41 ยท Forms and Validation

File Uploads and InputFile

Upload files in Blazor with InputFile: IBrowserFile, OnChange, MaxAllowedSize, OpenReadStream, multiple files, accept filters, saving to disk safely and showing upload progress.

Users upload avatars, CSV imports and documents. Blazor's InputFile component wraps <input type="file"> and gives your C# code an IBrowserFile for each chosen file. You then read the bytes through a stream. The tricky parts are limits, memory and safety, so most of this lesson is about doing it responsibly.

Blazor cannot run on this site, so the component code is read-only. The C# examples are stand-ins that show the stream-copy, limit and file-name logic with in-memory streams.

InputFile basics

HTML
@page "/upload"
@rendermode InteractiveServer

<InputFile OnChange="OnFilesChosen" accept=".png,.jpg,.jpeg" />

@if (message is not null)
{
    <p>@message</p>
}

@code {
    private string? message;
    private const long MaxBytes = 2 * 1024 * 1024;   // 2 MB

    private async Task OnFilesChosen(InputFileChangeEventArgs e)
    {
        var file = e.File;                            // single file
        if (file.Size > MaxBytes)
        {
            message = "File is larger than 2 MB.";
            return;
        }

        var path = Path.Combine(Env.ContentRootPath, "uploads", Path.GetRandomFileName());
        await using var target = File.Create(path);
        await file.OpenReadStream(MaxBytes).CopyToAsync(target);
        message = $"Saved {file.Name} ({file.Size:N0} bytes).";
    }
}

IBrowserFile gives you Name, Size, ContentType and LastModified, and OpenReadStream(maxAllowedSize) for the content.

Limits

  • OpenReadStream defaults to a 500 KB maximum. If the file is larger it throws an IOException. Pass your own limit as the argument.
  • Choose limits per purpose: a few MB for images, more for documents. Large uploads are better done with a normal HTTP endpoint (a minimal API or controller with streaming) than through the Blazor connection.
  • With Interactive Server, the bytes travel over the SignalR connection in chunks, which has a message-size setting (MaximumReceiveMessageSize, 32 KB by default for hub messages, but file chunks are handled by the framework). With WebAssembly, the browser reads the file and your code runs locally.

Multiple files

Add multiple and read GetMultipleFiles:

HTML
<InputFile OnChange="OnChosen" multiple accept="image/*" />

@code {
    private const int MaxFiles = 5;

    private async Task OnChosen(InputFileChangeEventArgs e)
    {
        foreach (var file in e.GetMultipleFiles(MaxFiles))
        {
            await Save(file);
        }
    }
}

GetMultipleFiles(max) throws if the user selected more than max, so catch the exception or check e.FileCount first.

Treat every file as hostile

The browser tells you the name and content type, but the user controls both. Rules:

  1. Never use file.Name as a path. It can contain .. or odd characters. Generate your own name (Path.GetRandomFileName() or a GUID) and keep the original only as display text, sanitised.
  2. Check the extension against an allow-list (.png, .jpg) and, for images, sniff the first bytes (the "magic number": PNG starts with 89 50 4E 47).
  3. Enforce a size limit on the server, not just the accept attribute (which only filters the picker dialog).
  4. Store uploads outside wwwroot unless they should be public, and never run or interpret them.
  5. Consider virus scanning and image re-encoding for public sites.
flowchart LR
  A["IBrowserFile"] --> B{"Size under limit?"}
  B -->|"no"| X["Reject"]
  B -->|"yes"| C{"Extension on allow-list?"}
  C -->|"no"| X
  C -->|"yes"| D{"Magic bytes match?"}
  D -->|"no"| X
  D -->|"yes"| E["Save with generated name"]

Check size, extension and content before saving, and name the file yourself.

Previewing images

For small images you can show a preview using a data URL (limit the size because the string lives in memory):

HTML
@if (previewUrl is not null) { <img src="@previewUrl" width="160" alt="Preview" /> }

@code {
    private string? previewUrl;

    private async Task OnChosen(InputFileChangeEventArgs e)
    {
        var resized = await e.File.RequestImageFileAsync("image/png", 320, 320);
        using var ms = new MemoryStream();
        await resized.OpenReadStream(1024 * 1024).CopyToAsync(ms);
        previewUrl = $"data:image/png;base64,{Convert.ToBase64String(ms.ToArray())}";
    }
}

RequestImageFileAsync resizes in the browser before the bytes reach your code, which saves bandwidth.

Progress

CopyToAsync does not report progress. Read in a loop and update a field. Remember StateHasChanged when you update inside a long loop on the server, and await Task.Yield() so the UI can render:

HTML
<progress value="@copied" max="@total"></progress>

@code {
    private long copied, total;

    private async Task Save(IBrowserFile file)
    {
        total = file.Size;
        copied = 0;
        var buffer = new byte[64 * 1024];
        await using var input = file.OpenReadStream(20 * 1024 * 1024);
        await using var output = File.Create(NewPath());
        int read;
        while ((read = await input.ReadAsync(buffer)) > 0)
        {
            await output.WriteAsync(buffer.AsMemory(0, read));
            copied += read;
            StateHasChanged();
            await Task.Yield();
        }
    }
}

Stand-in: copy with a limit and progress

C# Stand-in: stream copy with progress and a size guard

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Stand-in: safe names and magic-byte checks

C# Stand-in: never trust the file name or type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Common mistakes

  • Leaving the 500 KB default and getting an IOException for a normal photo.
  • Building a path from file.Name.
  • Reading a large file into one byte[] on the server (memory pressure); stream it instead.
  • Trusting accept or ContentType as validation.
  • Holding on to the IBrowserFile after the component is disposed.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the default maximum size OpenReadStream accepts?

    Larger files throw unless you pass a bigger maxAllowedSize to OpenReadStream.
  2. 2. Why should you not use file.Name to build the save path?

    Generate your own name and use the original only as sanitised display text.
  3. 3. Does the accept attribute on InputFile enforce which files can be uploaded?

    Users can bypass the picker filter, so validate extension, size and content in code.
  4. 4. Which method reads several selected files with a safety cap?

    GetMultipleFiles returns the selected IBrowserFile items and throws when more than the cap are chosen.

Summary

  • InputFile raises OnChange with IBrowserFile items; read them with OpenReadStream(max).
  • The default limit is 500 KB: set your own, and prefer streaming over buffering.
  • Validate size, extension and content bytes; generate your own stored file name.
  • Report progress by copying in chunks; use RequestImageFileAsync to shrink images in the browser.

Next: Form Patterns and Submit State