v0.0.2
Demos (demo panel, opens in a new tab)

File upload

A single or multiple file upload field with a drag-and-drop zone, progress and a list with previews.

zb:file-upload zubazar/ui-pro

PRO

This component is in Zubazar UI Pro; Zubazar UI Pro brings Zubazar UI with it. Installing Zubazar UI Pro →

Basic usage

Basic usage: view
BLADE

Pass the Livewire property the file is uploaded to with model.

blade
<zb:file-upload model="id_document" label="Identity document" accept=".pdf,image/*" hint="Front of the ID card · PDF or image" />
PropValues
modelLivewire property (WithFileUploads)
labelLabel above the field
titleHeading in the zone; default "Drop the file here"
hintDescription; written from the limits when not given

Multiple upload and limits

Multiple upload and limits: view
BLADE

With multiple, several files can be chosen; accept, max-size-kb and max-files are checked in the browser.

blade
<zb:file-upload model="documents" multiple accept=".pdf,.jpg,.png" :max-size-kb="2048" :max-files="5" label="Ticket documents" />
PropValues
multipletrue | false
accept.pdf,.jpg | image/* | application/pdf
max-size-kbPer-file limit in KB
max-filesMaximum number of files in the list (including saved ones)

Saved files (edit form)

Saved files (edit form): view
BLADE

Pass previously saved files with existing; they appear in the same list as new files.

blade
<zb:file-upload
    model="documents"
    multiple
    :max-files="5"
    :existing="$savedDocuments"
    remove-existing="removeSavedDocument"
/>
PropValues
existing[['id' => 7, 'name' => …, 'url' => …, 'size' => …, 'thumbnail' => …]]
remove-existingLivewire method called with the id

Livewire component

PHP

Use WithFileUploads in the component, define a property with the same name as model, and move the files to the permanent disk with store() when saving.

php
use App\Models\Ticket;
use Illuminate\Support\Facades\Storage;
use Livewire\Component;
use Livewire\WithFileUploads;

class TicketDocuments extends Component
{
    use WithFileUploads;

    public Ticket $ticket;

    /** @var array<int, \Livewire\Features\SupportFileUploads\TemporaryUploadedFile> */
    public array $documents = [];

    /** @var array<int, int> Saved documents to delete on save */
    public array $toDelete = [];

    protected function rules(): array
    {
        return [
            // 5 documents in total: saved ones count, the ones to delete do not.
            'documents' => ['array', 'max:'.max(0, 5 - $this->saved()->count())],
            'documents.*' => ['file', 'mimes:pdf,jpg,png', 'max:2048'],
        ];
    }

    public function updatedDocuments(): void
    {
        $this->validate(['documents.*' => $this->rules()['documents.*']]);
    }

    public function removeSavedDocument(int $id): void
    {
        $this->toDelete[] = $id;
    }

    public function save(): void
    {
        $this->validate();

        $this->ticket->documents()->whereKey($this->toDelete)->get()->each->delete();

        foreach ($this->documents as $document) {
            $this->ticket->documents()->create([
                'name' => $document->getClientOriginalName(),
                'path' => $document->store('tickets/'.$this->ticket->id, 'public'),
                'size' => $document->getSize(),
            ]);
        }

        $this->reset('documents', 'toDelete');
    }

    private function saved()
    {
        return $this->ticket->documents()->whereKeyNot($this->toDelete);
    }

    public function render()
    {
        return view('livewire.ticket-documents', [
            'savedDocuments' => $this->saved()->get()->map(fn ($document) => [
                'id' => $document->id,
                'name' => $document->name,
                'url' => Storage::disk('public')->url($document->path),
                'size' => $document->size,
            ]),
        ]);
    }
}

Classic form (without Livewire)

Classic form (without Livewire): view
BLADE

With name instead of model, the files go to the server when the form is submitted; the form must have enctype="multipart/form-data".

blade
<form method="POST" action="{{ route('tickets.update', $ticket) }}" enctype="multipart/form-data" class="space-y-4">
    @csrf
    @method('PUT')
    <zb:file-upload name="attachments" multiple accept=".pdf,.jpg,.png" :max-size-kb="2048" :max-files="5" :existing="$savedAttachments" removed-name="removed_attachments" />
    <zb:button type="submit">Save</zb:button>
</form>
PropValues
nameForm field; [] is appended when multiple
removed-nameHidden field for the ids of removed saved files

About

In a Livewire component (model) the files are uploaded as soon as they are chosen; in a classic form without Livewire (name) they go when the form is submitted. Besides the default look there are avatar and compact looks.

Props

The values the component takes. What are props and slots?

PropTypeDefaultDescription
model—nullLivewire property the files are uploaded to (WithFileUploads); either model or name is required
name—nullWithout Livewire: name of the form field; the files are submitted with the form
multiplebooleanfalseMultiple files
variant—'default''default' | 'avatar' (single round image) | 'compact' (single line)
accept—''Such as '.pdf,.jpg' or 'image/*'; checked in the browser
max-size-kb—nullPer-file limit in KB; checked in the browser
max-files—nullMaximum number of files in a multiple list (including saved ones)
remaining—nullNumber of files that can still be added in multiple mode (legacy; use max-files instead)
existing—[]Saved files: id, name, url, size (bytes), thumbnail
remove-existing—nullLivewire method called with the id when a saved file is removed
removed-name—nullWithout Livewire: name of the hidden field for the ids of removed saved files
sortablebooleanfalseReordering by dragging and with buttons (multiple)
sort-method—nullLivewire method called with the new order
batchbooleanfalseLivewire + multiple: the files of one choice go in order in one uploadMultiple request
label—nullLabel above the field
requiredbooleanfalseAdds * to the label; screen readers hear "required" in the name of the choose button. Write the rule on the server as well
title—nullHeading in the zone; defaults to "Drop the file here" / "Drop files here"
hint—nullDescription; written from the limits when not given
camerabooleanfalse"Take a photo" button on touch devices
show-errorsbooleantrueShows model and model.* validation errors
previewsbooleantrueblob: thumbnails of the chosen images; false shows a file icon (a CSP without blob: in img-src)
listbooleantrueThe kit's file list; false: the drop area alone (the page shows the files)

Advanced

11 examples

Sorting

Sorting: view
BLADE

With sortable, the files in a multiple list are reordered by dragging the handle or with the up/down buttons. Every change dispatches the file-upload-sorted event; if sort-method is given, that Livewire method is called with the new order.

blade
<zb:file-upload model="photos" multiple sortable sort-method="sortPhotos" accept="image/*" :existing="$savedPhotos" />
PropValues
sortabletrue | false (multiple only)
sort-methodLivewire method called with the new order

Batch upload

Batch upload: view
BLADE

With batch (Livewire and multiple), the files of one choice go together in one $wire.uploadMultiple() request, in the order they were chosen. It is meant for forms that process the files together, e.g. variant images matched in order to the selected variants.

blade
<zb:file-upload model="variant_images" multiple batch accept="image/*" :max-size-kb="2048" label="Variant images" hint="The images are matched in order to the selected variants" />
PropValues
batchtrue | false (Livewire, multiple)

Avatar

Avatar: view
BLADE

variant="avatar" draws a round picker for a single image, with a preview and "Change" and "Remove" buttons. Pass the saved photo with existing; without a thumbnail, the url becomes the preview.

blade
<zb:file-upload model="profile_photo" variant="avatar" label="Profile photo" :max-size-kb="1024" :existing="$savedPhoto" remove-existing="removePhoto" />
PropValues
variant'default' | 'avatar' | 'compact'

Compact

Compact: view
BLADE

variant="compact" is a single-line picker for tight forms that files can also be dropped onto. With multiple, the row shows the number of files and the files are listed below.

blade
<zb:file-upload model="invoice" variant="compact" label="Invoice" accept=".pdf" :max-size-kb="2048" />

Taking a photo

Taking a photo: view
BLADE

When camera is given, a "Take a photo" button appears on touch devices such as phones and tablets; a photo taken with the rear camera is added straight to the list. The button does not appear on devices used with a mouse.

blade
<zb:file-upload model="return_photo" accept="image/*" camera hint="Photo of the damaged product" />
PropValues
cameratrue | false

Validation errors

Validation errors: view
BLADE

The component shows the model's validation errors itself: a documents error below the field, and an error for one file such as documents.2 on that file's row. If you show the messages on the page yourself, pass :show-errors="false".

blade
<zb:file-upload model="documents" multiple accept=".pdf" :max-files="5" />
PropValues
show-errorstrue | false

Saving the order

PHP

sort-method receives the new order on every sort; write the order of saved files right away and store temporary uploads in the same order on save. Always limit the ids to your own record.

php
public function sortPhotos(array $order): void
{
    foreach ($order as $position => $item) {
        if ($item['type'] === 'existing') {
            $this->product->photos()->whereKey($item['id'])->update(['position' => $position]);
        }
    }

    // Temporary uploads in the same order too (id = getFilename()).
    $uploadOrder = collect($order)->where('type', 'upload')->pluck('id')->flip();

    $this->photos = collect($this->photos)
        ->sortBy(fn ($photo) => $uploadOrder[$photo->getFilename()] ?? PHP_INT_MAX)
        ->values()
        ->all();
}

Classic form: controller

PHP

Validate on the server: the file type and size should match accept and max-size-kb (the max: rule takes KB); the number of files is calculated by subtracting the saved files from the max-files limit. After a validation error, the browser cannot restore the chosen files; attachments and attachments.* errors are listed below the component.

php
public function update(Request $request, Ticket $ticket): RedirectResponse
{
    $removed = $request->input('removed_attachments', []);
    $remaining = 5 - $ticket->attachments()->whereKeyNot($removed)->count();

    $request->validate([
        'attachments' => ['array', 'max:'.max(0, $remaining)],
        'attachments.*' => ['file', 'mimes:pdf,jpg,png', 'max:2048'],
        'removed_attachments' => ['array'],
        'removed_attachments.*' => ['integer'],
    ]);

    $ticket->attachments()->whereKey($removed)->get()->each->delete();

    foreach ($request->file('attachments', []) as $attachment) {
        $ticket->attachments()->create([
            'name' => $attachment->getClientOriginalName(),
            'path' => $attachment->store('tickets/'.$ticket->id),
            'size' => $attachment->getSize(),
        ]);
    }

    return back();
}

Upload state and events

BLADE

Since the component dispatches Livewire's upload events (livewire-upload-start, -finish, -error) itself, wire:loading and wire:target work with the model name; you can lock the save button until the queue finishes. If the file-upload-reset event is dispatched on the window with { model } ({ name } in a classic form), the running upload is cancelled and waiting and failed rows are cleared (e.g. when a modal closes).

blade
<zb:file-upload model="documents" multiple />

<div class="mt-4 flex justify-end gap-2">
    <zb:button variant="white" x-data x-on:click="$dispatch('file-upload-reset', { model: 'documents' })">Cancel</zb:button>
    <zb:button wire:click="save" wire:loading.attr="disabled" wire:target="documents,save">Save</zb:button>
</div>
PropValues
file-upload-resetDispatched on the window; { model: 'documents' }
file-upload-remove-existing{ model, name, id }
file-upload-sorted{ model, name, order }

Uploading without Livewire

JS

To upload with model on a page without a Livewire component, register your own transport (e.g. directly to a storage service). upload returns { promise, cancel } for each file; concurrency is how many files are sent at once.

js
import { registerFileUpload } from '@zubazar/ui-pro';

document.addEventListener('alpine:init', () => {
    registerFileUpload(window.Alpine, {
        transport: {
            concurrency: 3,
            upload(file, { onProgress }) {
                const request = new XMLHttpRequest();
                const promise = new Promise((resolve, reject) => {
                    request.upload.onprogress = (event) => onProgress((event.loaded / event.total) * 100);
                    request.onload = () => (request.status < 300 ? resolve(JSON.parse(request.response).id) : reject(new Error('failed')));
                    request.onerror = () => reject(new Error('failed'));
                    request.onabort = () => reject(Object.assign(new Error('cancelled'), { cancelled: true }));
                });
                const body = new FormData();
                body.append('file', file);
                request.open('POST', '/uploads');
                request.setRequestHeader('X-CSRF-TOKEN', document.querySelector('meta[name=csrf-token]').content);
                request.send(body);

                return { promise, cancel: () => request.abort() };
            },
        },
    });
});

Fields per file and the drop area alone

Fields per file and the drop area alone: view
BLADE

The row slot is drawn under every file row, with Alpine's item (key, id, name, size, status) in scope. :list="false" hides the kit's list, so your page shows the files.

blade
<zb:file-upload name="attachments" multiple label="Documents">
    <zb:slot:row>
        <div class="grid gap-2 sm:grid-cols-2">
            <input data-zb-control type="text" x-bind:name="'attachment_names[' + item.key + ']'" x-bind:value="item.name" aria-label="Document name" class="rounded-sm border-line-strong bg-field text-sm">
            <select data-zb-control x-bind:name="'attachment_types[' + item.key + ']'" aria-label="Document type" class="rounded-sm border-line-strong bg-field text-sm">
                <option value="invoice">Invoice</option>
                <option value="delivery-note">Delivery note</option>
            </select>
        </div>
    </zb:slot:row>
</zb:file-upload>
PropValues
rowSlot; under every row, item in scope
listfalse: the drop area alone

Developer notes

Events, hooks and details
  • The whole zone is a button: a file is dropped, or chosen by clicking or with Enter/Space. While the zone has focus, an image pasted from the clipboard is added too.
  • The chosen file shows in the list with its preview or file type icon, its size and its status; on a single-file field a new file replaces the previous one.
  • There is no Livewire on this page, so the upload is simulated; a file with "hata" in its name shows the error row.
  • In a multiple upload each file is uploaded separately with its own progress bar. Queued files wait as "Waiting"; a running transfer can be cancelled, and a failed or cancelled one retried.
  • A file that breaks a limit is not uploaded and shows in the list with the reason (e.g. "too large (at most 2 MB)"). The browser check is only quick feedback; write the same rules on the server too.
  • A saved file's name opens in a new tab, and saved files count toward the max-files limit. The remove button dispatches the file-upload-remove-existing event; if remove-existing is given, that Livewire method is also called with the id.
  • A url in existing must be an http(s) or in-app address; otherwise the file name is not a link. A thumbnail may also be a small inline image (data:image/png;base64,…, not SVG) or a CDN address in the //host form.
  • The order items are { type: 'existing', id } for a saved file and { type: 'upload', id } for a temporary upload (id is the file's getFilename() value). In a form without Livewire, the files are added to the form field in list order.
  • A batch set is appended to the property like single uploads (an array or Collection grows, a null property becomes the set itself). The updated hook sees the set at once; if you empty the property in the hook, only the new set arrives each time.
  • In a batch upload the rows share one progress; cancel and errors affect the whole set, and a retry sends the remaining files together again. A file removed from a set still waiting leaves the set; a file removed while it is being sent cancels the set.
  • On the avatar, the upload percentage appears over the image; without accept, image/* is used, and multiple is ignored.
  • On a single-file field the error appears directly on the file row; documents.2 is the file at index 2 of the Livewire property.
  • For a multiple field make the property an empty array (public array $documents = []); each file is uploaded separately and added to it.
  • Files first go to Livewire's temporary folder; validation in the updated hook shows the error on the file's row as soon as the upload finishes. Reset the property after saving; the list follows the server, so it empties by itself.
  • For a temporary file removed from the list, the component calls $wire.removeUpload() (on a single-file field it sets the property to null); no separate method is needed.
  • In a classic form the files are kept in a hidden <input type="file" name="attachments[]"> field; the list can be edited before submitting, and changes reach the field at once.
  • The ids of removed saved files go in hidden fields named with removed-name (removed_attachments[]); when the form is reset (reset), the list is cleared too.
  • In your own transport the promise resolves with the file's id; if it is rejected with an error carrying cancelled: true, the row is marked as cancelled. With Livewire the files go one after another, since Livewire handles uploads to the same property one by one.
  • In a classic form bind the name of the field inside row to the file's key with x-bind:name; in Livewire write e.g. x-on:change="$wire.set('documents.' + item.id + '.name', $event.target.value)".
  • Add data-zb-control to the fields you write; they get the kit's form field look.

Events

EventdetailDescription
file-upload-remove-existing{ model, name, id }Sent from the component when a saved (existing) file is removed from the list; it bubbles.
file-upload-sorted{ model, name, order }Sent when the order changes. order is an array of { type: 'existing', id }, { type: 'new', name } or { type: 'upload', id }.
file-upload-reset (listens){ model } | { name }Dispatched on window, it cancels running uploads and clears queued and failed rows.
Zubazar UI · ZubazarDesigned for people.