livewire·rust

File uploads

The browser uploads to a signed URL, the server keeps the file in a temporary directory, and the component's field holds only its name.

upload.rs
#[derive(Default, LivewireComponent)]
#[livewire(view = "livewire.upload")]
pub struct Upload {
    pub photo: String,
}
Live exampleopen ↗

Choose a file and pick one once; the bytes go to the signed temporary URL, and the field carries only the reference.

The client is upstream's, unchanged, so its handshake is the contract: ask the component for a URL, POST the file to that URL, then name the temporary file back to the component. This port implements all three steps on the local disk.

The component's field

A file property is a string. Nothing is uploaded while the page renders; the field is empty until the browser finishes an upload and names the file.

#[derive(Default, LivewireComponent)]
#[livewire(view = "livewire.upload")]
pub struct Upload {
    pub photo: String,
}

A multiple upload holds Vec<String> instead. Each entry is a temporary file name with the prefix the client understands, livewire-file:<name>. It crosses the wire as an ordinary string, so no synthesizer is involved.

The two endpoints

Both sit under the application's endpoint prefix, the same hashed prefix as the update route.

MethodPathDoes
POST/livewire-{8 hex}/upload-fileStores the files a signed URL was made for
GET/livewire-{8 hex}/preview-file/{filename}Serves a temporary file whose extension may be previewed

The upload handshake

  1. The input fires change; the client calls _startUpload(name, fileInfos, multiple).
  2. The server answers with a dispatches effect named upload:generatedSignedUrl and parameters {name, url}.
  3. The client POSTs a FormData whose repeated field is files[], with Accept: application/json and the CSRF header.
  4. The endpoint answers {"paths":["livewire-file:<name>", ...]}.
  5. The client calls _finishUpload(name, tmpFilenames, multiple, append), which writes the field.

A signed URL names the component it was made for, expires with the configured upload window, and carries a lower-case hex SHA-256 over the application key, the component ID, and the expiry, joined by |:

/livewire-1a2b3c4d/upload-file?component=kOa7wQ2cJv9tLbX1mR4d&expires=1796400000&signature=9f2c...c41

Nothing is stored by _startUpload. The signature covers the component and the expiry, not the file, because the file is not known when the URL is made.

The four upload calls

CallParametersEffect
_startUploadnameupload:generatedSignedUrl {name, url}
_finishUploadname, tmpFilenames, multiple, appendupload:finished {name, tmpFilenames}
_uploadErrorednameupload:errored {name}
_removeUploadname, tmpFilenameupload:removed {name, tmpFilename}

These four are the runtime's own. They never reach a component method of the same name, and an upload call never skips the render: the response carries the new field and the markup that shows it.

_finishUpload writes the field, then the response renders. When the field already holds an array, the names are added to it. Otherwise a single upload writes the first name and a multiple one writes the whole array. _removeUpload deletes the file only when the name it was given is safe: non-empty, with no .., /, or \.

Temporary storage

The file is written to the configured directory of the application's default local disk, which is storage/app/private:

storage/app/private/livewire-tmp/7kQ2xN4pR8sT1vW6yZ3b.jpg

The name is twenty random alphanumeric characters. An extension is appended only when the browser's file name has one of one to eight ASCII alphanumeric characters; else the stored file has none. The browser's name is never used as a path, so a ../ in a file name cannot leave the directory.

What keeps it safe

The endpoint is public, so the crate treats every byte as a stranger's:

Preview

preview-file/{filename} serves the stored bytes with the content type matching the extension. The extension must be one the configuration lists in preview_mimes; a name that is unsafe or an extension that is not listed is 403, and a file that is not there is 404.

The content types are a fixed table: png, gif, bmp, svg, jpg/jpeg, webp, wav, mp3/mpga, m4a, mp4, mov, avi, wmv, and pdf. wma is on the allowlist but has no entry in that table, so it is served as application/octet-stream.

Status codes

StatusWhen
401The URL's query does not parse, has no component, expires, or signature, or the signature is wrong or expired
403The preview name is unsafe, or its extension is not in preview_mimes
404The preview file is missing, or the multipart body has no usable files[] part
422A file is larger than the configured max rule

The 422 body is JSON with a message the browser can show, and the limit in kilobytes:

{"message":"The file may not be larger than 12288 kilobytes."}

Uploads are not guarded by the payload limits, which belong to the update endpoint. The size limit here is the configuration's rule, and the check runs before any file is written.

Configuration

Everything lives in the temporary_file_upload section, whose defaults mirror upstream's.

KeyDefaultRead by this port
diskthe default diskRecorded only; the file goes to the default local disk
rulesrequired, file, max:12288Only max:<kilobytes>; the multipart form requires a file on its own
directorylivewire-tmpYes, under storage/app/private
middleware.max_attempts60Through config.upload_throttle(), which the route does not apply yet
middleware.decay_seconds60Same
preview_mimes16 extensionsYes, for the preview endpoint
max_upload_time5 minutesYes, as the signed URL's lifetime
cleanuptrueRecorded only; the scheduled task is the application's

To read the size rule yourself, livewire::uploads::max_bytes(&config.temporary_file_upload.rules) returns the limit in bytes, or None when no readable max: rule exists.

Cleanup

An upload nobody finished stays in the directory after its URL expires, so it must be deleted. livewire::uploads::prune takes the directory and a maximum age, deletes the regular files at least that old, and returns how many it deleted. A missing directory deletes nothing and is not an error.

Application::configure().with_schedule(|schedule, _| {
    schedule
        .call(|| async {
            let _ = livewire::uploads::prune(
                std::path::Path::new("storage/app/private/livewire-tmp"),
                std::time::Duration::from_secs(24 * 60 * 60),
            )
            .await;
        })
        .name("livewire:prune-uploads")
        .daily();
});

The command upstream uses for S3 exists for parity, and answers about the disk it finds:

cargo run -- livewire:configure-s3-upload-cleanup

On any disk whose name is not s3, it prints upstream's own error, Configuration ['livewire.temporary_file_upload.disk'] is not set to a disk with an S3 driver., and exits zero. With disk = "s3" it reports that this port does not talk to S3 and names the scheduled prune instead. No bucket lifecycle is ever changed.

There is no S3 disk. The disk key is not read, the upload URL is always a local path, and upload:generatedSignedUrlForS3 is never dispatched. Everything on this page is the local disk.