Skip to content

File Upload ​

FilePond for file fields, and a hand-built cropper for avatars.

FilePond is the only upload vendor in src/vendor/; the avatar cropper is this repository's own code and is described under Avatar cropping below.


FilePond ​

MIT · vendored · lazy-loaded on first [data-av-uploader]

html
<div class="av-field">
  <label class="av-field__label" for="documents">Choose files or drop them here</label>

  <input type="file" class="av-input" id="documents" name="documents[]" multiple
         accept=".pdf,.docx,image/*"
         data-av-uploader
         data-av-uploader-max-files="10"
         data-av-uploader-max-size="10MB"
         aria-describedby="documentsHint">

  <p class="av-field__hint" id="documentsHint">
    PDF, Word, or images. Up to 10 files, 10 MB each.
  </p>
</div>

Without JavaScript this is a working native file input that submits with the form. And if the vendor fails to load it stays one — initUploader releases the data-av-init claim and returns, rather than leaving a half-enhanced control behind. A file field is not a progressive nicety; it is often the only reason the form exists.

Three plugins are vendored alongside it: file-validate-type, file-validate-size and image-preview. ImageResize and ImageExifOrientation are not vendored, so client-side resizing and rotation correction are not available on this control. (The avatar cropper does apply EXIF orientation — it had to, and does it itself.)

Attributes ​

AttributeDefaultEffect
data-av-uploader—Required marker; the module scans input[type="file"][data-av-uploader]
data-av-uploader-max-files10 when multiple, else 1Also decides allowMultiple
data-av-uploader-max-size(none)'25MB', '800KB', a bare byte count
data-av-uploader-url(none)Passed to FilePond as server. Without it the control is a picker and the form does the posting
data-av-uploader-label"Drag files here or browse"Replaces the idle label

There are no chunked uploads: server is a plain URL string, so a file is one request. For anything over about 20 MB you want a resumable protocol, which is an application decision with a server half.

accept is the single source of the type rule ​

The module rewrites accept to MIME types before FilePond.create, and the reason is a trap worth knowing rather than an implementation detail.

FilePond's type plugin matches with exact string equality (bar a trailing *), and a file's type is a MIME type. So an extension entry can never equal it: accept=".pdf,.docx,image/*" — ordinary, valid markup — silently refuses every PDF and Word document the author meant to allow, with a message naming the extension it just rejected. The attribute that says what is permitted becomes the reason nothing is.

MIME types are equally valid in accept, so rewriting it keeps the native picker filtering correctly and makes both halves read the same list. The rewrite must happen on the DOM rather than through an option, because the plugin registers accept in FilePond's SET_ATTRIBUTE_TO_OPTION_MAP — the attribute wins over anything passed to create.

FilePond replaces the input, it does not enhance it ​

This is the fact everything else about the integration follows from. The original <input> is removed from the DOM, a fresh input.filepond--browser is created carrying the name, and the original id is moved onto the root <div>. Two bugs came out of not knowing that:

  1. The data-av-init claim went with the removed element, so destroyContent — which walks [data-av-init] — could never find the control again and the root survived every navigation. The root is re-claimed and the instance is keyed by it, which is what makes teardown reachable.
  2. <label for> now pointed at a <div>. A div is not a labelable element, so that is not a weaker association, it is none at all: no accessible name and a dead click target. The label is re-pointed at the browse input, which aria-labelledby alone would not fix — that would name the control and leave the label dead to the pointer.

registerPlugin is global and runs once rather than per scan. The flag lives in the module and not on the vendor object, because FilePond here is an ESM module namespace object, which is sealed — assigning a property to it throws. That is a real difference from the UMD vendors in this codebase, where the export is an ordinary object and the same mistake would go unnoticed.

Styling ​

FilePond renders and owns the item list, the progress ring and the action buttons; there is no .av-upload-item in this product. src/scss/plugins/_filepond.scss re-points the vendor's own selectors at tokens, inside @layer plugins:

Vendor selectorRe-pointed to
.filepond--panel-root--av-surface-sunken with a dashed --av-border-default
.filepond--drop-label--av-text-secondary
.filepond--label-action--av-color-primary-text — the only interactive text in the control
.filepond--item-panel--av-surface-raised
.filepond--file-action-buttonToken fills, plus a real :focus-visible ring
.filepond--progress-indicator--av-text-on-primary

The vendored stylesheet is kept rather than replaced — 17 KB of drop-zone mechanics, item enter/leave transitions and progress geometry is structure worth taking. About a dozen colour literals inside it are holes in any dark theme, and those are what the partial covers. Each rule repeats the vendor's own selector rather than relying on source order, because both files sit in plugins.

Events ​

EventDetail
av:uploader:ready{ el, instance } — el is the FilePond root, instance the pond

For progress, completion and errors, subscribe to FilePond's own callbacks through the instance handed to you by av:uploader:ready.


Avatar cropping ​

A separate component, and not Cropper.js — no cropping vendor is in src/vendor/. Cropper.js and its family are 40–60 KB to do arithmetic the browser already provides, and this repository has taken the same decision for the calendar, the carousel, the virtual list and every date picker.

The markup is a shared partial, html/_partials/avatar-upload-dialog.html, so the same dialog serves the settings page, the profile hero and anything else that grows an avatar later:

html
<dialog class="av-dialog av-dialog--lg" id="avatarUpload"
        data-av-avatar-upload
        data-av-avatar-target="#profilePhoto"
        data-av-avatar-max-size="2MB"
        data-av-avatar-min="200"
        data-av-avatar-output="512"
        aria-labelledby="avatarUploadTitle">
  <div class="av-dialog__inner">
    <div class="av-dialog__body">
      <div class="av-avatar-upload">
        <label class="av-avatar-drop" data-av-avatar-dropzone>
          <span class="av-avatar-drop__title">Choose a photo, or drop one here</span>
          <p class="av-avatar-drop__hint">PNG, JPG or WebP · at least 200×200 · up to 2 MB.</p>
          <input type="file" accept="image/png,image/jpeg,image/webp"
                 aria-describedby="avatarUploadStatus" name="file">
        </label>

        <div class="av-avatar-editor" data-av-avatar-editor hidden>
          <div class="av-avatar-stage">
            <canvas width="480" height="480" tabindex="0" role="img"
                    data-av-avatar-canvas
                    aria-label="Crop area. Drag the photo, or use the arrow keys to move it
                                and the plus and minus keys to zoom."></canvas>
            <span class="av-avatar-stage__mask"></span>
            <span class="av-avatar-stage__ring"></span>
          </div>

          <div class="av-avatar-tools">
            <input class="av-range" type="range" min="1" max="4" step="0.01" value="1"
                   data-av-avatar-zoom data-av-slider aria-label="Zoom" name="avatar-zoom">
          </div>
        </div>

        <p class="av-avatar-upload__status" id="avatarUploadStatus"
           data-av-avatar-status role="status" aria-live="polite"></p>
      </div>
    </div>
  </div>
</dialog>
AttributeEffect
data-av-avatar-uploadOn the <dialog>; marks the whole component
data-av-avatar-targetSelector for the avatar this dialog writes to
data-av-avatar-max-sizeRejected above this, with the reason announced
data-av-avatar-minMinimum source edge in pixels
data-av-avatar-outputExported edge in pixels; the result is WebP at quality 0.9

The six details that decide whether this is a cropper or a picture of one ​

  1. The preview and the file come out of one draw call. paint() takes a context and a size, and serves the canvas on screen, both live previews and the export. A cropper with a separate export path is two implementations of one transform, and the one nobody watches is the one that ships the avatar with the head cut off.
  2. The crop is a circle, because the avatar is. Cropping square and letting CSS round it later shows the reader corners they are about to lose. The mask is drawn where the crop is.
  3. The image can never leave the frame. Scale has a floor that covers the circle, and the offsets are clamped whenever either changes. A cropper that lets you drag the photo off the frame will be used to do exactly that.
  4. EXIF orientation is applied on the way in. A phone photograph carries its rotation as metadata, and drawImage from a decoded bitmap ignores it unless asked — so a portrait selfie arrives on its side and the person crops a sideways face without being told why. createImageBitmap(file, { imageOrientation: 'from-image' }) is the whole fix, with an <img> fallback where the option is missing.
  5. The arrow keys move the photo, and the zoom is a real input[type=range] rather than two buttons, so its value is announced and settable. A drag-only cropper cannot be used without a pointer at all — which is the accessibility hole every cropping vendor ships with.
  6. The object URL is revoked — one per chosen file, and per replaced preview. Held for the life of the document otherwise: the leak nobody sees, because nothing looks broken.

The canvas is role="img" with the instructions in its accessible name, because there is nothing else in the stage to announce. Reopening the dialog clears the last person's photograph, the object URL, the bitmap, the file input and the status line — a close listener, not a cancel one, so it runs however the dialog was dismissed.

Important — the crop is a client-side convenience. Re-crop and re-encode server-side too. A crafted upload bypasses the client entirely.


Drop targets ​

Two ship, and both are a <label> wrapping a real <input type="file"> rather than a bare <div> with drag handlers:

ClassWhereState class
.av-avatar-dropThe avatar dialog.is-over
.av-import-dropThe CSV import panel.is-over

Wrapping the input is what makes the affordance work without JavaScript: the click target, the keyboard path and the accessible name all come from the label, and :focus-within paints the ring when the hidden input takes focus. [aria-invalid="true"] on the drop target is how a rejected file is shown, alongside the announcement in the status region.

Drag-and-drop is never the only path. There is always a visible way to browse, and the underlying <input type="file"> stays keyboard-operable.


Security ​

This template has no server, so nothing in this section is something AdminVora does for you. It is the list of controls the backend behind these controls must implement, and every one of them is mandatory. File upload is the highest-risk feature in most admin panels.

Client-side validation — the accept attribute, max-size, the type plugin — is UX only. It tells an honest user what will be accepted. It stops no attacker at all.

1. Validate the type server-side, by content ​

php
// ❌ Trivially bypassed — the client controls both
$request->file('doc')->getClientOriginalExtension();
$request->file('doc')->getClientMimeType();

// ✅ Reads the actual file
$mime = $request->file('doc')->getMimeType();          // uses finfo
$allowed = ['application/pdf', 'image/jpeg', 'image/png', 'image/webp'];
abort_unless(in_array($mime, $allowed, true), 422);

For images, verify they are decodable:

php
abort_unless(@getimagesize($file->getRealPath()) !== false, 422);

2. Never trust the filename ​

php
$safe = Str::uuid() . '.' . $this->extensionFor($mime);
$path = $file->storeAs('uploads', $safe, 'private');

A filename like ../../../.env or shell.php.jpg is a real attack. Generate your own name.

3. Store outside the web root ​

php
'private' => [
    'driver' => 'local',
    'root'   => storage_path('app/private'),
    'visibility' => 'private',
],

Serve through a controller that checks authorisation:

php
public function show(Upload $upload)
{
    $this->authorize('view', $upload);
    return response()->file(Storage::disk('private')->path($upload->path), [
        'Content-Disposition' => 'attachment; filename="' . $upload->original_name . '"',
        'X-Content-Type-Options' => 'nosniff',
    ]);
}

4. Force download for user content ​

Content-Disposition: attachment
X-Content-Type-Options: nosniff
Content-Security-Policy: default-src 'none'; sandbox

An uploaded SVG is an HTML document. Served inline from your origin, it can run JavaScript with your cookies. Either force download or strip scripts:

php
$svg = (new enshrined\svgSanitize\Sanitizer())->sanitize($contents);

5. Serve from a separate origin where possible ​

usercontent.example.com rather than app.example.com. Same-origin uploads inherit your cookies and your CSP.

6. Limit size at every layer ​

nginx
client_max_body_size 20M;
ini
upload_max_filesize = 20M
post_max_size = 21M
php
$request->validate(['file' => 'required|file|max:20480']);

All three server layers are required. data-av-uploader-max-size is none of them.


Checklist ​

  • [ ] Native <input type="file"> present, and still working if the vendor fails to load
  • [ ] accept written once on the input, and read by both the picker and the plugin
  • [ ] Server validates MIME by content, not by extension or client MIME
  • [ ] Filenames regenerated server-side
  • [ ] Files stored outside the web root
  • [ ] Content-Disposition: attachment + X-Content-Type-Options: nosniff on downloads
  • [ ] SVG uploads sanitised or forced to download
  • [ ] Size limits at web server, runtime, and application layers
  • [ ] <label for> still points at something labelable after the vendor mounts
  • [ ] Drop targets have a keyboard path and a visible browse control
  • [ ] Rejections are announced, not only outlined
  • [ ] Object URLs revoked when the source they preview is replaced
  • [ ] destroy() reachable — the claim is on the element the vendor left behind

Read next: Form Enhancements.

Documentation for @creativeigniter/adminvora