File upload
A property typed IBrowserFile - or a list of them - renders a file picker built on Blazor's
InputFile, keeps the chosen files on the model and lists them back with their sizes.
Accept(...) and MaxFileSize(...) become the picker's own accept filter
and rules: the filter is only a suggestion the user can switch off in the dialog, so the field judges
every file that actually arrives, and says what is wrong with it.
Pick a
.txt as the CV, then a PDF over 2 MB: each is refused with its own reason. Attach four
documents and Items(max: 3) counts them like any other list. The chosen files are listed with their
sizes, and Clear selection takes them away. The files stay on the model until the submit, where the handler reads them with
OpenReadStream() as it would from InputFile. [FileExtensions] on the model
does what Accept does here. To send each file the moment it is chosen - with progress, cancel and
retry - and keep what the server returned instead, see uploads.
View source
@page "/files"
<BormView State="_state" OnValidSubmit="HandleSubmit" SubmitText="Upload" ShowErrorSummary="true" />
@code {
private readonly DocumentUpload _model = new();
private BormState _state = default!;
protected override void OnInitialized()
{
var schema = BormBuilder.For<DocumentUpload>()
.Title("Send us your documents")
.Field(x => x.Applicant, f => f.Required().Autocomplete("name"))
.Field(x => x.Resume, f => f
.Accept(".pdf,.doc,.docx")
.MaxFileSize(2 * 1024 * 1024)
.Required("Please attach your CV.")
.Help("PDF or Word, up to 2 MB."))
.Field(x => x.Attachments, f => f
.Accept("image/*,.pdf", multiple: true)
.MaxFileSize(5 * 1024 * 1024)
.Items(max: 3, message: "Attach at most three documents.")
.Help("Optional. Up to three images or PDFs, 5 MB each."))
.Build();
_state = new BormState(schema, new BormModelDataAccessor(_model));
_state.StateChanged += OnStateChanged;
}
private void OnStateChanged() => InvokeAsync(StateHasChanged);
private async Task HandleSubmit(BormState state)
{
// The files are read here, exactly as from Blazor's InputFile.
if (_model.Resume is { } cv)
{
await using var stream = cv.OpenReadStream(maxAllowedSize: 2 * 1024 * 1024);
// ... await storage.SaveAsync(cv.Name, stream) ...
}
}
}