NE.Standard

Files

File transfer runs beside the live connection, not on it: upload is a plain multipart/form-data POST and download a GET, both authenticated from the same session cookie the page render writes. Every operation is scoped to the session, so a file id alone is never enough to read a file.

Uploading

FileInputComponent and ImageInputComponent upload as soon as the user picks a file — the picker sends it immediately, and the returned selection id lands in the component's own bound value. Until then the bound value does not hold the file, so a submit of the form (OnSubmit, Enter in a SubmitOnEnter field) waits for the uploads of the pickers with the same SetFormId, then reads the selection with them, the form's other OnSubmit values as they stood at the press. A shelf's square whose upload fails is taken off and named on the shelf's validation line, and the submit goes without it. The wait has no timeout: it ends with the upload. The upload, download and content endpoints all authenticate from the session cookie and honour UISecurityOptions.DefaultPolicy: under Authenticated, an anonymous session gets 401 from every one of them, even on a page marked [UIAllowAnonymous] — a public upload form on a closed site needs the policy left open or the visitor signed in.

new FileInputComponent()
    .BindSelectionId(nameof(ProfileController.AvatarSelectionId))
    .SetAccept("image/png,image/jpeg")
    .SetMaxFileSize(2 * 1024 * 1024)
    .SetMultiple(false)

SelectionId is a string? with UIBindingMode.TwoWay — bind it to read what was uploaded; Value only controls what the field displays. MaxFileSize is picker chrome: a client can simply not send it, so the real limit is enforced on the server (see below). On the page it refuses a larger file with a word on the field's validation line — "The file is larger than 2 MB.", in the page's language (ui.file.oversized, taking {limit} as a file size); a multi-file input or a shelf takes the rest and names the files it left out (ui.file.leftout), and the next pick clears the line. ImageInputComponent carries the same SelectionId, plus Variant (UIImageInputVariant), Fit, PlaceholderIcon, Caption and a Value that holds the picture actually shown — a URL the controller owns, shown as a local preview until the controller answers with one of its own. Setting SelectionId null or empty clears a single picture — its preview, its name and its handle — and the control shows Value again, as an empty SelectionIds clears a shelf of several; a pick still uploading stays.

The file input's variants (UIFileInputVariant) are Row (the default field row), Tiles (a multi-file square shelf with an + add tile) and Shelf (a headerless row of squares and nothing else, each with its remove and its upload's progress, taking several files whatever Multiple says — the messenger's attachments above a composer). An empty Shelf is not on the page at all (but for a validation line, where a file too large lands). It takes any file by default (or narrows by Accept): a picture as its thumbnail, any other file as a square with its kind's glyph — a PDF, text, a document, a spreadsheet, slides, an archive, audio, video, code, or a blank page — over its name and size; a FileTileComponent (below) draws the same square for a feed that shows what was sent. The image input's variants (UIImageInputVariant) are Picture (a drop area with the picture as its preview, or a multi-picture tile shelf when SetMultiple(true) is set), Avatar and Inline (a row like the file input's), always accepting image/* by default. A shelf's chooser is opened from elsewhere: OpenPickerEffect(fileInput) (or OpenPickerEffect(inputId)) opens a file or image input's chooser from another control, and since a browser opens one only inside the reader's own press, it belongs in an interaction. SetDropTargetId(panel) (or SetDropTargetId(componentId)), on a file or an image input, makes another component of the view a drop target: files dropped on it, and pictures pasted into it, go into the input by the input's own Accept, MaxFileSize and Multiple, the target outlined while files are over it; a paste that carries text stays the field's. A target the view does not hold is refused when the view compiles.

A single picture — the Picture, Avatar and Inline variants — can be framed before it is sent: SetCrop(UIImageCrop.Square) or UIImageCrop.Circle opens a crop dialog on the picture the reader picked, dropped or pasted. The picture stands under a fixed frame; a drag (mouse or finger) or the arrow keys move it, the wheel, a pinch, + and − or the slider zoom it, up to four times filling the frame. Done uploads the square the frame holds — the circle is only the frame an avatar is seen through, the file is square — and Cancel or Escape upload nothing and leave the input as it was. The crop is written at the frame's own pixels up to SetCropSize(px) (1024 unset), never scaled up, in the picture's own type where that is JPEG, PNG or WebP and as a PNG otherwise. It all happens in the browser, so the controller reads an already cropped file and MaxFileSize weighs the crop. A shelf, or an input with Multiple, takes its pictures as they are: a crop on one fails the render.

new ImageInputComponent()
    .SetVariant(UIImageInputVariant.Avatar)
    .SetCrop(UIImageCrop.Circle)
    .SetCropSize(256)
    .BindValue(nameof(ProfileController.Photo))
    .BindSelectionId(nameof(ProfileController.PhotoUpload))
new FileInputComponent("attachments")
    .SetVariant(UIFileInputVariant.Shelf)
    .SetDropTargetId("composer")
    .SetMaxFileSize(10 * 1024 * 1024)
    .BindSelectionIds(nameof(ChatController.Attachments))

UIIconButtons.Attach().InteractOn(EventNames.Click, new OpenPickerEffect("attachments"))

A file that was sent is a FileTileComponent, the shelf's square for a file in a component of its own: the kind's glyph (UIFileGlyphs.For(fileName, contentType), or its own Icon), the name on up to two lines and whole as its tooltip, and the size written by the page in the reader's language ("1.5 MB", "1,5 МБ"). It is a 6rem square unless its Width says otherwise. The same size anywhere else — a file dialog's line under its name, a toast — is a UIFileSize in a phrase, written by the same formatter (localization): new UIFileSize(file.Size).Phrase(), or ("size", new UIFileSize(file.Size)) among other words. Loading turns a ring in the glyph's place, for a file still on its way; OnClick (or OnClickWithItemKey in a row) makes it pressable as a surface is — to open or download the file (DownloadFileEffect) — and a set or bound Clickable gates it. SetUrl(address) makes it a link to the file instead, opened or downloaded by the browser, in a new tab or copied as a surface's is; AccessibleName names it where its file's name is not what it does. A message's attachments are a wrap of them:

new ItemsViewComponent()
    .BindItems(nameof(Message.Files), UIBindingScope.Relative)
    .SetOrientation(UIOrientation.Horizontal)
    .SetLayoutType(UIItemsLayoutType.Wrap)
    .SetTemplate(new FileTileComponent()
        .BindFileName(nameof(SentFile.Name), UIBindingScope.Relative)
        .BindFileSize(nameof(SentFile.Size), UIBindingScope.Relative)
        .BindContentType(nameof(SentFile.ContentType), UIBindingScope.Relative)
        .BindLoading(nameof(SentFile.IsPending), UIBindingScope.Relative)
        .OnClick(nameof(ChatController.OpenFile), UIAction.ArgRelative("id", nameof(SentFile.Id)))
    )

A controller reads the selection through Context.Uploads (IUIUploadService):

[UICommand]
public async Task SaveAvatarAsync(CancellationToken cancellationToken)
{
    if (string.IsNullOrWhiteSpace(AvatarSelectionId))
        return;

    UIUploadSelection selection = await Context.Uploads
        .GetSelectionAsync(Context.Handle, AvatarSelectionId, cancellationToken)
        .ConfigureAwait(false);

    AvatarSelectionId = null;

    if (selection.Files.Length == 0)
        return;

    UIUploadedFile file = await Context.Uploads
        .OpenAsync(Context.Handle, selection.Files[0].FileId, cancellationToken: cancellationToken)
        .ConfigureAwait(false);

    await using (file.ConfigureAwait(false))
    {
        // file.Content is the readable stream; file.Metadata has FileName/ContentType/Size.
    }
}

Check the selection id first: it is null until the user picks something, and GetSelectionAsync throws ArgumentException on an empty one. Clearing it once read keeps the same selection from being taken twice. A selection id that names nothing — swept, or another session's — gives an empty selection rather than an error.

GetSelectionAsync(handle, selectionId) returns a UIUploadSelection — Files (UIUploadFile[]) and the convenience member SingleFile. OpenAsync/OpenManyAsync open one or more uploaded files as a UIUploadedFile (Metadata + Content, disposable). CopyToAsync/CopyManyToAsync copy straight to a destination stream instead of handing one back. All four take an optional IProgress<double> — a real server-side copy loop over already-staged content, so the number means what it says.

Every UIUploadFile.FileId is issued by the store, never taken from the client — a client-chosen id could collide with, or guess at, another client's file. Its FileName is the client's text: the web's upload endpoint keeps its last segment after / or \, drops control characters and cuts it at 255 characters (an empty, . or .. name is no file). Show it; never make it a path or trust it for a type.

Limits

UIFileOptions, configured on the application builder in ConfigureApplication:

application.ConfigureFiles(files =>
{
    files.MaxFileSize = 10 * 1024 * 1024;
    files.MaxFilesPerSelection = 8;
    files.MaxUploadBytesPerSession = 64 * 1024 * 1024;
    files.UploadRetention = TimeSpan.FromHours(1);
    files.DownloadRetention = TimeSpan.FromMinutes(5);
    files.StorageRoot = "/var/ne-uploads";
});
Option Default Meaning
MaxFileSize 32 MB the largest single file, enforced at the upload endpoint while the part streams, not after buffering it; past it the request is answered 413
MaxFilesPerSelection 16 how many files one upload may carry; past it the request is answered 400
MaxUploadBytesPerSession 256 MB how much one session may hold in uploads at once, until the sweep removes them; a request past it is answered 413, and a file that would cross it is stopped where it crosses
MaxUploadBytesTotal 4 GB how much every session together may hold in uploads at once, counting those still arriving — a session costs a visitor one page load, so the per-session limit alone does not bound the disk; an upload that would cross it is answered 413, and zero or null is no such limit
MaxDownloadBytesPerSession 256 MB how much one session may hold in uncollected staged downloads at once; staging a download that would cross it fails
MaxDownloadBytesTotal 4 GB how much every session together may hold in uncollected staged downloads at once; zero or null is no such limit
UploadRetention 1 hour how long an uploaded selection survives before the sweep removes it
DownloadRetention 5 minutes how long a staged download waits to be fetched
CleanupInterval 5 minutes how often the sweep runs, so content lives its retention plus up to one interval
StorageRoot the application's own folder under the system temp directory, ne.standard.ui.files/<entry assembly>-<hash of its base directory> where the default store keeps content; its sweep deletes what the store does not claim, so a root shared by two applications would lose each one's files to the other

Storage itself is IUIFileStore. The framework registers FileSystemUIFileStore by default: content on local disk under StorageRoot, metadata in process memory — so it serves one process, and its uploads do not survive a restart. A farm, or a host that wants blob storage, registers its own IUIFileStore in ConfigureServices; the default only fills what is still empty (see web hosting). Every method on the store takes the session id — that is the security boundary an implementation must not drop. The per-session limit asks the store how much a session holds (GetUploadedBytesAsync); a store that does not implement it reports 0, which leaves only MaxFileSize and MaxFilesPerSelection in force.

Downloading

A controller stages a download through Context.Downloads (IUIDownloadService):

[UICommand]
public async Task DownloadReportAsync(CancellationToken cancellationToken)
{
    byte[] content = Encoding.UTF8.GetBytes("stage,seconds\nresolve,0.8\n");

    _ = await Context.Downloads
        .DownloadAsync(Context.Handle, "deploy-report.csv", "text/csv", content, cancellationToken)
        .ConfigureAwait(false);
}

DownloadAsync takes a Stream or a byte[], stages it (within MaxDownloadBytesPerSession and MaxDownloadBytesTotal), and returns a UITransferResult (Success, Cancelled, Error — mutually exclusive, with Ok()/Cancel()/Fail(error) factories). There is no IProgress<double> here: the server hands the browser a URL and the browser does the fetching, so the server cannot observe it. Staging sends a DownloadFileEffect (RequestPath, FileName) to the page, as Context.SendEffectsAsync sends an effect, and the page turns it into a browser download; the path is single-use and the token behind it is dropped once read — a second fetch, or a fetch from another session, is 404, never 403, so the token tells nothing about what it named. The answer is Cache-Control: no-store, so nothing between the server and the browser keeps a copy of one session's file.

Protected content

A staged download is fetched once and gone. Content the application keeps around — an avatar, a chat background — is fetched by an <img> or a link whenever the browser likes, and it is scoped to the user rather than to one connection's session. That is IUIContentProvider:

public sealed class MediaService(AppDatabase database, IUIContentAddressResolver content) : IUIContentProvider
{
    public string AddressOf(string mediaId) => content.AddressOf(mediaId);

    public async Task<UIContent?> ResolveAsync(UIContentRequest request, CancellationToken cancellationToken = default)
    {
        if (request.Session.UserId is not string userId)
            return null;

        StoredMedia? media = await database.FindMediaAsync(request.Key, cancellationToken).ConfigureAwait(false);

        if (media is null || (!media.IsPublic && media.OwnerId != userId))
            return null;

        return new UIContent
        {
            Content = new MemoryStream(media.Bytes, writable: false),
            ContentType = media.ContentType,
            Immutable = true
        };
    }
}

AppDatabase, FindMediaAsync and StoredMedia stand for the application's own storage; the graph demo's PlannerPictures (addons/Graph/examples/DemoApp.Graph/Planner/PlannerPictures.cs) is a complete one over SQLite, for pictures everyone who may open the page may see.

Register it as a service — services.AddSingleton<IUIContentProvider>(...) — and name a stored item's address with the injected IUIContentAddressResolver.AddressOf(key) (a controller reaches the same resolver through Context.Content), bound to a component's Source. The host serves it at GET /_ne/content/{**key} — a key may contain / — resolving the session from the same cookie the file endpoints use. The provider is the whole of the authorization: it sees who asks (UIContentRequest.Session) and what for (UIContentRequest.Key), and answers null for anything that session may not have — the host turns null into 404, never 403, so a key's existence is not revealed to someone who may not read it. No session at all answers 401 before the provider is asked, and a cross-site request 403, as the upload read-backs do.

UIContent carries Content, ContentType, an optional FileName (set it to make the browser save rather than show the content inline), and Immutable — set it only when the key always answers the same bytes, which is what a content-addressed key buys; the response is then private, max-age=31536000, immutable, otherwise private, no-cache. Either way it is private: the answer depended on who asked, so no shared cache may keep it.

Content and downloads are always served inert: a Content-Security-Policy that runs nothing, and HTML, XML or SVG sent as an attachment even without a FileName, so a file a user uploaded cannot run as a page of the application when it is opened directly. A script, a stylesheet, a WebAssembly module or a type that does not parse goes out as application/octet-stream, so no page runs one as its <script src> or stylesheet either. An <img> or a CSS background ignores the policy, so embedding is untouched. WebEndpointOptions.InlinePassiveContent (off by default) shows a type that runs nothing — a PDF, a raster image, plain text, audio, video — without the policy, so a PDF opens inline in Chromium; HTML, XML, SVG and a script stay inert whatever it says.

A controller does not need any of this to read the content itself — it already has the application's services. The endpoint exists for the browser's own fetches.