📤 File Upload & Media Components
Status: Implemented and documented (Feb 2026)
📖 Overview
Comprehensive file upload system with image editing, asset picking, and multi-file support.
🧱 Components
⬆️ FileUploader (ui/media/FileUploader.svelte)
Multi-file uploader with:
- Drag & drop support
- Click to browse
- File type & size validation
- Edit (✏️) per pending file — on an image the button is titled Edit: it dispatches
editImageand the host opens ImageEditModal. On any other file it is titled Rename: it dispatcheseditFileand the host opens FileEditModal. The edited file replaces the pending one (replaceFile()). Nothing opens on its own: on Upload the host receives the pending files as they are (the Files page'spendingImageFilesqueue inroutes/(app)/files/+page.svelteis never filled) - Restore original (↩️) on every edited file, cropped or renamed (
editedIndices), Remove on every file - Preview for images via backend thumbnail API
Hosts:
- Files page, Static Resources —
on:uploadsends each file throughuploadFile(file, undefined, 'personal'): a file uploaded there is personal (see Scope of uploaded files). - Files page, Broker Reports (
accept=".csv,.xlsx,.xls") — the selection opens the Assign Brokers dialog: one broker per file or Assign all to, pre-filled when the user can edit exactly one broker (Viewer brokers are left out), and Upload (n) enabled only once every file has a broker. All the files of one confirmation share abatch_id(generateUUID()), so they form one report set. - BrokerImportFilesModal — the report files of one broker.
✂️ ImageCropper (ui/media/ImageCropper.svelte)
cropperjs v2 based image cropper (Web Components):
- Free crop with L-shaped corner handles
- Zoom (overlay buttons and mouse wheel) works on the selection first: zoom-in shrinks it by
10% until it covers 50% of the image (
MIN_SELECTION_COVERAGE), then zooms the image by 0.1; zoom-out enlarges it by 10% up to 90% (MAX_SELECTION_COVERAGE), then zooms the image out - Rotation (15° steps, −15° / +15°) relative to selection center
- Flip horizontal/vertical
- Aspect ratio given by the host (
aspectRatio;0orNaN= free); the ratio buttons live in ImageEditModal - Selection clamped to canvas bounds
- Middle-mouse-button drag for background translation
🖼️ ImageEditModal (ui/media/ImageEditModal.svelte)
Full image editing modal (extends ModalBase):
It opens only when a host asks: the ✏️ Edit button of FileUploader (Files page), or the upload path of ImagePickerWrapper (below) — never by itself when a file is picked.
- Confirm button — Crop & Upload when
uploadOnCompleteistrue(the default, used by ImagePickerWrapper); Crop when it isfalse, as on the Files page after ✏️, where the cropped file goes back to the pending list - Scope — the
scopeprop (defaultcommon) goes touploadFile()on Crop & Upload. ImagePickerWrapper keeps the default, so an image uploaded through a picker is common; the Files page passespersonal, though withuploadOnCompletefalse the modal uploads nothing itself - Presets (
IMAGE_PRESETSinlib/utils/files/imageCrop.ts): buttons Avatar (200×200), Icon (broker-icon, 64×64) and Custom (free size), shown whileallowPresetChange(defaulttrue). Theasset-iconpreset (256×256) has no button: only a host can set it - Round preview — a toggle for the ellipse overlay, on by default for Avatar and Icon
- Ratio buttons 1:1, 16:9, 4:3, 3:4 and Free, shown only with Custom
- Output — width and height are capped at the selection and keep its ratio; Scale goes from 0.01 to 1
- Format —
.png,.jpgor.webp, defaulting to the source file's type. Quality (JPEG and WebP only) moves with −/+ in 10-point steps from 10 to 100, default 90 - Reset All (header) puts zoom, rotation and flip back and re-centres the selection
(
resetAll()) - Closing with changes asks Discard changes? — Discard & Close
📄 FileEditModal (ui/media/FileEditModal.svelte)
Simple file rename modal (extends ModalBase):
- Rename file before upload
- Used for PDFs, CSVs, and other non-image files
- Also available for BRIM import files
scope(default none: the backend's rule decides) goes touploadFile()whenuploadOnCompleteistrue. The Files page passespersonal. WithuploadOnCompletefalse — the Files page after ✏️, BrokerImportFilesModal — nothing is uploaded: the renamed file goes back to the pending list
🔎 AssetPickerModal (ui/media/AssetPickerModal.svelte)
3-tab asset picker modal (extends ModalBase):
- Existing: Browse uploaded files with DataTable or FileGrid: the common files and the user's
own personal ones, even for an administrator, whose
GET /uploadslists every file. The list loads once per opening (existingLoaded). Confirming a personal file shares it first (D36-1, below) - URL: Enter a URL with live preview and circular overlay
- Upload: dispatches
uploadwith the picked image; the host (ImagePickerWrapper) opens ImageEditModal, which uploads it common
Used for: broker icons, user avatars, and any image URL field.
📸 ImagePickerWrapper (ui/media/ImagePickerWrapper.svelte)
(This component is an invisible logic wrapper and has no UI of its own) Wraps the full AssetPicker → ImageEdit flow:
- Opens AssetPickerModal
- If upload selected → opens ImageEditModal, with its default scope
common - Returns final URL to parent
👤 UserAvatar (ui/media/UserAvatar.svelte)
An account's avatar in a 24 px circle, or its initial when it has none (lot N69-4, decision D8 a). Its one host today is the UserRow of the Users tab.
- Props:
username,avatarUrl(string | null, the account'savatar_url) andtestId, thedata-testidof its root. The root carriesdata-avatar="image"ordata-avatar="initial". - An image uploaded to the app, an
avatarUrlstarting with/api/v1/uploads/, is asked for as its 48×48 preview, sharp on a 2× screen:img_preview=48x48is appended after?, or after&when the address already has a query. Any other address is used as it is. The image is aLazyImage(circle,placeholder="avatar", the username asalt), so the preview of an uploaded file goes through the preview cache (imagePreviewCache). - Without an avatar (
nullor empty): the first character of the trimmed username, upper-cased (?for an empty name), on a neutral disc: the scheme of the user pickers (UserSearchSelect), the rolesbg-lf-neutralandtext-lf-muted, with no colour of its own per user; the letter isaria-hidden. - Tests:
lib/features/settings/users/UserRow.avatar.test.ts(URA-01 to URA-04, in./dev.py test front-utility component-unit) mounts it through the row, with the realLazyImageand afetchthat never answers: the image asked for, the initial, and the toggle still opening its panel.
📁 FileGrid (files/FileGrid.svelte)
Shared grid view component used in both /files page and AssetPickerModal.
mode="browse"withshowActions(the Files page): each card offers Download, Preview (when the file has one), Copy Link, the scope switch and Delete. The switch (file-grid-scope-<id>, withdata-scope) needs theonscopechangeprop and a file whosecan_deleteis notfalse; it callsonscopechange({file, scope})with the opposite scope: the lock icon of a common file asks forpersonal, the users icon of a personal one forcommon. Delete (file-grid-delete-<id>,ondelete({id})) shows on the samecan_deletecondition. The cards carry no scope badge: the list view shows itmode="select"(AssetPickerModal,showActions={false}): single selection, no actions
📋 FilesTable (files/FilesTable.svelte)
The DataTable of the Files page, both tabs, and of a broker's
Uploaded Reports: type="static" or
type="brim". The Report set badges of type="brim" are in
Badges in FilesTable.
- Visibility column (
scope,type="static"only): a badge,infofor a common file (Shared) anddefaultfor a personal one (Personal), with an enum filter on the two values, URL keyscope - Row actions
shareandmakePersonal(type="static", only with theonScopeChangeprop):shareon a personal file callsonScopeChange(file, 'common'),makePersonalon a common oneonScopeChange(file, 'personal'); both only when the file'scan_deleteis notfalse - Delete row action: hidden when the row's
can_deleteisfalse, on both types (UploadFileInfo.can_delete;can_deleteof theGET /brokers/import/filesitems). The bulk delete belongs to the host'sSelectionBar: the Files page leaves those files out (below), BrokerImportFilesModal sends them and the server refuses them with403
🔐 Scope of uploaded files
Every static upload is common (every signed-in user sees it) or personal (its uploader and the
admins): developer decision 36. The backend rule, older files included, is in
Uploaded Files: Common and Personal; the frontend
chooses the scope of what it uploads, and lets the user change it.
Client — frontend/src/lib/utils/files/upload.ts, with the type UploadScope (UploadedFile['scope']:
'common' | 'personal') in frontend/src/lib/types/files.ts:
uploadFile(file, description?, scope?)—POST /api/v1/uploads, returns the file's URL. The multipart fieldscopeis sent only when given; without it, the backend's rule decides (images common, the rest personal)setUploadScope(fileId, scope)—PATCH /api/v1/uploads/{id}with{scope}, returns theUploadedFileas the backend now describes it. Only the uploader and the admins may: anyone else gets403or404
Who uploads with which scope:
| Upload | scope sent |
|---|---|
Files page, Static Resources (handleUpload in routes/(app)/files/+page.svelte) |
personal |
An image picker: ImagePickerWrapper → ImageEditModal with its default scope (ProfileTab and WelcomePage avatars, BrokerForm icon, AssetModal icon) |
common |
| ImageEditModal and FileEditModal on the Files page | personal, though after ✏️ they upload nothing (uploadOnComplete false) |
FileEditModal at its default scope (BrokerImportFilesModal, which uploads nothing through it) |
none: the backend's rule |
Files page (routes/(app)/files/+page.svelte):
- FilesTable's
onScopeChangeand FileGrid'sonscopechangeboth go torequestScopeChange(file, scope).commonis applied at once;personalfirst opens a warningConfirmModal(files-scope-confirm), since the other users lose the file, also where it serves as an icon or a photo.applyScopeChange()callssetUploadScope()and puts the returned file in place of the row - the
scopeURL filter (urlFilterColumns) also filters the grid view (staticGridColumns) - the bulk delete (
handleBulkDeleteFiles, both tabs) deletes only the selected files whosecan_deleteis notfalse(deletableSelection()); the others stay, reported byfile.delete.skippedwith a warning toast
Image picker (AssetPickerModal). What a picker returns is shown to other users, so a personal image picked there becomes common, with a notice (D36-1):
- the Existing tab keeps the common files and the user's own:
scope === 'common', oruploaded_by_user_idequal to the id ofcurrentUser(lib/stores/app/auth) - confirming a personal file, necessarily the user's own, first calls
setUploadScope(id, 'common'), and dispatchesselectonly once that succeeds, withfile.scope.shared-on-pickand an info toast. On failure:file.scope.change.failedwith an error toast, noselect, and the picker stays open. Use Selected is disabled meanwhile (confirming) - a common file is handed back at once, its scope untouched
App events — through notify() (lib/stores/app/notify.svelte.ts), kept in
window.__lf.events for the E2E; the toast is a field of the same call:
| Event | Emitted by | detail |
Toast |
|---|---|---|---|
file.scope.changed |
Files page | {fileId, scope} |
success: uploads.scope.nowShared or uploads.scope.nowPersonal |
file.scope.change.failed |
Files page; AssetPickerModal | {fileId, scope, reason}; {fileId, scope: 'common'} |
error: uploads.scope.changeFailed |
file.scope.shared-on-pick |
AssetPickerModal | {fileId} |
info: uploads.scope.sharedOnPick |
file.delete.skipped |
Files page, bulk delete | {count, isBrim} |
warning: uploads.deleteSkipped |
The page's other file events (file.uploaded, file.upload.failed, file.deleted,
file.deleted.bulk, file.delete.failed) carry no toast. The texts are the uploads.scope.* keys
of frontend/src/lib/i18n/files/<lang>.json.
📂 Files
frontend/src/lib/
├── features/files/
│ ├── FileGrid.svelte
│ └── FilesTable.svelte
└── components/ui/media/
├── AssetPickerModal.svelte
├── FileEditModal.svelte
├── FileUploader.svelte
├── ImageCropper.svelte
├── ImageEditModal.svelte
├── ImagePickerWrapper.svelte
├── LazyImage.svelte
├── UserAvatar.svelte
└── index.ts
🖥️ Backend Support
- Image preview API:
GET /api/v1/uploads/file/{id}?img_preview=WxH, answered withCache-Control: private, max-age=3600 - File serving:
GET /api/v1/uploads/file/{id}sendsContent-Disposition: inlinefor the stored types ofINLINE_SAFE_MEDIA_TYPES(PDF, JSON, plain text, CSV and the common images), so the PDF fallback of the preview, an<iframe>, displays instead of downloading; any other type and?download=trueare an attachment, and every response carriesX-Content-Type-Options: nosniff(H6-2, How a file is served) - Preview cache: Size-based (
PREVIEW_CACHE_MAX_MBin.env, default 50MB), TTL 1h, invalidated on delete - No-op for small images: If requested size ≥ original, serves file directly without processing
- Scope: every upload is
common(every signed-in user sees it) orpersonal(its uploader and the admins).POST /api/v1/uploadstakes an optional multipart fieldscope; without it, a file whose validated type (below) isimage/*is stored common and any other file personal.PATCH /api/v1/uploads/{id}with{"scope": "common"}or{"scope": "personal"}changes it, for the uploader or an admin. EveryUploadFileInfocarriesscopeandcan_delete: whether the requesting user may delete the file and change its scope. The full rule, older files included: Uploaded Files: Common and Personal - Seed avatars: 30 default avatar PNGs copied to
custom-uploads/on first startup viaseed_default_avatars(), with uploader0(the system): they are common - Off the event loop: the handlers of uploaded files (
api/v1/uploads.py) run the service's synchronous disk work (save_upload,list_uploads,get_upload_info,get_upload_path,set_upload_scope,delete_upload) throughasyncio.to_thread - Upload utility:
uploadFile()infrontend/src/lib/utils/files/upload.ts— single FormData creation point;setUploadScope()sits beside it (see Scope of uploaded files) - Size formatting: Centralized i18n-aware
formatBytes()in the samefrontend/src/lib/utils/files/upload.ts
✅ Validation
Client side (FileUploader):
- File type checking against
acceptprop - File size checking against global
max_file_upload_mbsetting
Server side:
- Size —
get_max_upload_mb()(max_file_upload_mb, default 10) is enforced on bothPOST /uploadsandPOST /brokers/import/upload:413above the limit. - Static files (
validate_upload_security()inservices/files/static_uploads.py) — the extension must not be inBLOCKED_EXTENSIONS(.exe,.dll,.sh,.py,.js,.jar, …); whenpython-magic(libmagic) loads, the content's detected type must not be inBLOCKED_MIME_TYPES, otherwise the type is guessed from the extension (mimetypes). A declared type that differs from the detected one is only logged. A refused file returns400. - Static delete and scope change —
DELETEandPATCH /uploads/{id}belong to the uploader or a superuser. Another user gets403on a common file (Cannot delete files uploaded by other users, Cannot change files uploaded by other users) and, on a personal one, the404of a file that does not exist. The UI offers delete and the scope switch only on a file whosecan_deleteis notfalse(FilesTable, FileGrid). - Broker reports — EDITOR or OWNER on the target broker (
403), an empty file is refused (400),batch_idmust be a UUID (422). There is no server-side extension check: only the uploader'sacceptlimits them to CSV and Excel.
The two families differ deliberately: someone else's personal static file answers 404, so its existence is not
revealed, while the broker report routes answer 403 to a user without access to the file's broker.