> ## Documentation Index
> Fetch the complete documentation index at: https://flex-fields.bjanczak.com/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Examples target Filament 5. Verify optional dependencies before configuring integrations.
> Upload transfer completion, permanent storage and record acceptance are separate milestones. Native and Spatie image conversions retain the original.

# Resumable chunk uploads

> Set up resumable uploads in FLEX Fields with private local chunks, a tus endpoint, server-side validation and scheduled cleanup.

Use chunk uploads when your users need to resume an interrupted transfer without sending the entire file again. FLEX writes chunks to a private staging directory and keeps the committed byte offset in your database. Once the last chunk arrives, your application verifies the assembled file and attaches it to the form or saves it through Media OS.

> [!NOTE]
>
> The standard `FlexFileUpload` picker sends a whole file through Livewire. Chunking is an opt-in integration for an upload interface you control. Your application creates and authorizes each session and decides when to attach the verified file.

Use this guide when file bytes should pass through your Laravel application. For browser uploads that send parts straight to object storage, see [Amazon S3 and Multipart uploads](https://flex-fields.bjanczak.com/docs/file-upload-s3.md#direct-uploads-with-s3-multipart).

## 1. Install session tables explicitly

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
php artisan fff:uploads:install
```

This publishes one migration into your application's `database/migrations` directory. It does **not** run it. Review the migration, then run your normal application migration process:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
php artisan migrate
```

The default tables are `fff_upload_sessions` and `fff_upload_parts`. They store transfer state and part metadata; they do not replace your application's gallery table or Spatie's media table.

If you choose a separate database connection or table prefix below, edit the published migration to use that same connection and prefix in **both** `up()` and `down()`. The default published migration deliberately uses the default connection and `fff_` names.

## 2. Configure local limits

Merge this section into `config/filament-flex-fields.php`:

```php theme={"theme":{"light":"github-light","dark":"github-dark"}}
'file_upload' => [
    'resumable' => [
        'enabled' => true,
        'connection' => null,
        'table_prefix' => 'fff_',
        'retention' => ['enabled' => false],
        'http' => [
            'enabled' => false,
            'prefix' => 'flex-fields/uploads',
            'middleware' => ['web', 'auth', 'throttle:120,1'],
        ],
        'local' => [
            'root' => storage_path('app/private/flex-upload-sessions'),
            'disk' => 'local',
            'max_bytes' => 256 * 1024 * 1024,
            'chunk_bytes' => 8 * 1024 * 1024,
            'expires_after_seconds' => 86400,
            'verification_lease_seconds' => 300,
        ],
    ],
],
```

| Setting | Purpose |
| - | - |
| `enabled` | Allows resolving the optional session services. Default: `false`. |
| `connection` | Laravel database connection for session state; `null` uses the default. |
| `table_prefix` | Session table prefix. Match the installed migration. |
| `local.root` | Absolute private staging directory, outside public storage. `null` uses the path shown above. |
| `local.disk` | Logical identity of this local transport. Bytes are written under `root`; this does not select an arbitrary Flysystem adapter. |
| `local.max_bytes` | Maximum complete file size, in bytes. Default: 256 MiB. |
| `local.chunk_bytes` | Maximum bytes per accepted chunk. Default: 8 MiB. Choose the same or a smaller chunk size in the client. |
| `local.expires_after_seconds` | Session lifetime, 60–604800 seconds. Default: one day. |
| `local.verification_lease_seconds` | Time before a superseded verification attempt may be retried, 30–3600 seconds. |

All upload-serving workers must see the same local staging filesystem and database. Independent container-local directories cannot resume one another's uploads. Your proxy's request body limit must accommodate a chunk, and request timeouts must accommodate its transfer. The declared total size still needs application-level authorization and quota checks before creating a session.

### Example limits for two deployments

| Use case | Maximum file | Chunk size | Session lifetime |
| - | - | - | - |
| PDFs and photos on slower mobile connections | `64 * 1024 * 1024` | `2 * 1024 * 1024` | `3600` seconds |
| Larger files over a managed internal network | `256 * 1024 * 1024` | `8 * 1024 * 1024` | `86400` seconds |

For the 8 MiB example behind Nginx, allow a slightly larger request body at the upload route, for example `client_max_body_size 10m;`. Check any limits imposed by a reverse proxy or CDN too. The application still enforces its own maximum chunk and total file sizes.

## 3. Create a server-owned session

This example adds a chunk uploader to an existing post editor. It assumes your application has an `App\Models\Post` model and an `update` policy. The Laravel session associates the upload ID with the post, so the browser does not choose its owner or tenant.

Add a session-creation route in `routes/web.php`:

```php theme={"theme":{"light":"github-light","dark":"github-dark"}}
use App\Models\Post;
use Bjanczak\FilamentFlexFields\Support\Media\Uploads\LocalResumableUploads;
use Bjanczak\FilamentFlexFields\Support\Media\Uploads\LocalUploadOptions;
use Bjanczak\FilamentFlexFields\Support\Media\Uploads\UploadScope;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Route;

Route::post('/posts/{post}/gallery-uploads', function (
    Request $request,
    Post $post,
    LocalResumableUploads $uploads,
    LocalUploadOptions $limits,
) {
    Gate::authorize('update', $post);

    $data = $request->validate([
        'name' => ['required', 'string', 'max:180', 'regex:/\A[a-zA-Z0-9][a-zA-Z0-9 ._()-]*\z/'],
        'bytes' => ['required', 'integer', 'min:1', 'max:'.$limits->maxBytes],
    ]);

    $scope = new UploadScope(
        owner: 'user:'.$request->user()->getAuthIdentifier(),
        tenant: '',
        field: 'post-gallery',
        draft: 'post:'.$post->getKey().':'.$request->session()->getId(),
    );

    $upload = $uploads->create($scope, $data['name'], (int) $data['bytes']);
    $request->session()->put('post_gallery_uploads.'.$upload->id, $post->getKey());

    return response()->json([
        ...$upload->snapshot(),
        'uploadUrl' => route('filament-flex-fields.uploads.tus', ['id' => $upload->id]),
        'chunkBytes' => $limits->maxChunkBytes,
    ], 201);
})->middleware(['auth', 'throttle:20,1']);
```

Apply your file-count and storage quota rules before calling `create()`. For a multi-tenant application, resolve the active tenant on the server, scope the post lookup to that tenant, and use its ID in `UploadScope` at creation and on every subsequent request. Remove session associations after acceptance or expiry. For high-volume uploads or resume across authenticated devices, keep associations in your application database with an expiration date.

## 4. Receive chunks through the PHP service

Use this API when your application owns the HTTP controller. Streams are borrowed: the caller closes them after the operation.

```php theme={"theme":{"light":"github-light","dark":"github-dark"}}
use Bjanczak\FilamentFlexFields\Support\Media\Uploads\UploadChecksum;

// $input is the current request's raw resource stream.
// $scope was reconstructed and authorized for this request.
$next = $uploads->append(
    scope: $scope,
    id: $sessionId,
    offset: $validatedOffset,
    input: $input,
    length: $validatedContentLength,
    checksum: $checksumHeader === null
        ? null
        : UploadChecksum::fromHeader($checksumHeader),
);

return response()->json($next->snapshot());
```

For a checksum header, use `sha256 ` followed by the Base64-encoded binary SHA-256 digest of **that chunk**. SHA-1 is also supported for protocol compatibility. A mismatched offset or checksum does not advance the committed offset. After a lost response, read the current owned session and resume from its reported offset rather than assuming the last request failed:

```php theme={"theme":{"light":"github-light","dark":"github-dark"}}
$current = $uploads->retrieveOwnedSession($scope, $sessionId);
$offset = $current->offset;

// Cancellation applies to this authorized temporary session.
$uploads->abort($scope, $sessionId);
```

## Optional tus HTTP endpoint

Set `resumable.http.enabled` to `true` **after** binding an application implementation of `UploadRequestAuthorizer`. Both `resumable.enabled` and `resumable.http.enabled` must be true. The endpoint refuses requests without an authorizer.

```php theme={"theme":{"light":"github-light","dark":"github-dark"}}
use App\Uploads\PostUploadAuthorizer;
use Bjanczak\FilamentFlexFields\Support\Media\Uploads\Http\UploadRequestAuthorizer;

// In your application service provider's register() method:
$this->app->bind(UploadRequestAuthorizer::class, PostUploadAuthorizer::class);
```

Your implementation has this contract:

```php theme={"theme":{"light":"github-light","dark":"github-dark"}}
namespace App\Uploads;

use App\Models\Post;
use Bjanczak\FilamentFlexFields\Support\Media\Uploads\Http\UploadRequestAuthorizer;
use Bjanczak\FilamentFlexFields\Support\Media\Uploads\UploadScope;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;

final class PostUploadAuthorizer implements UploadRequestAuthorizer
{
    public function resolve(Request $request, string $sessionId): ?UploadScope
    {
        $user = $request->user();
        $postId = $request->session()->get('post_gallery_uploads.'.$sessionId);

        if ($user === null || (! is_int($postId) && ! is_string($postId))) {
            return null;
        }

        $post = Post::find($postId);

        if ($post === null || Gate::forUser($user)->denies('update', $post)) {
            return null;
        }

        return new UploadScope(
            owner: 'user:'.$user->getAuthIdentifier(),
            tenant: '',
            field: 'post-gallery',
            draft: 'post:'.$post->getKey().':'.$request->session()->getId(),
        );
    }
}
```

Set `file_upload.resumable.http.enabled` to `true` once the binding is in place. Keep `web`, `auth` and throttling in the route middleware for this recipe. The authorizer runs on every request, including `OPTIONS`.

Generate the URL through the named route:

```php theme={"theme":{"light":"github-light","dark":"github-dark"}}
$url = route('filament-flex-fields.uploads.tus', ['id' => $session->id]);
```

| Request | Headers and behavior |
| - | - |
| `HEAD` | `Tus-Resumable: 1.0.0`; returns `Upload-Offset` and `Upload-Length`. |
| `PATCH` | Version header, `Content-Type: application/offset+octet-stream`, `Upload-Offset`, request `Content-Length`, optional `Upload-Checksum`. Success: 204 and the new offset. |
| `DELETE` | Version header; aborts the owned temporary upload. |
| `OPTIONS` | Advertises checksum, termination and expiration support; still requires authorization. |

For clients that cannot issue `PATCH`, `POST` with `X-HTTP-Method-Override: PATCH` is supported. This is **not** the tus Creation extension: applications create the admitted session separately. Concatenation is not implemented.

Keep authentication, CSRF protection and route throttling appropriate to your application. The default `web` middleware means browser writes need the application's CSRF token. Changing a route prefix may require rebuilding Laravel's route cache. Cross-origin access is not enabled automatically.

Relevant response codes include 409 for offset/state conflict, 410 for expired/unavailable sessions, 412 for an unsupported protocol version, 413 for an oversized chunk and 460 for a checksum mismatch. Reconcile an ambiguous transfer with `HEAD` before sending more bytes.

### Send chunks from a same-origin form

Pass the file, the session-creation response and your Laravel CSRF token to this function. It returns only when the server has all the bytes. If the request fails, calling the function again starts with `HEAD` and resumes from the server's current offset. Keep the same file for the same session.

```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
async function sendChunks(file, session, csrfToken, onProgress = () => {}) {
  const url = new URL(session.uploadUrl, location.href);
  if (url.origin !== location.origin) {
    throw new Error("Expected a same-origin upload endpoint.");
  }

  const version = { "Tus-Resumable": "1.0.0" };
  const head = await fetch(url, { method: "HEAD", headers: version, cache: "no-store" });
  if (!head.ok) throw new Error(`Cannot resume this upload (${head.status}).`);

  const readNumber = (response, name) => {
    const header = response.headers.get(name);
    const number = Number(header);
    if (header === null || !Number.isSafeInteger(number) || number < 0) {
      throw new Error(`Invalid ${name} returned by the upload endpoint.`);
    }
    return number;
  };

  const total = readNumber(head, "Upload-Length");
  let offset = readNumber(head, "Upload-Offset");
  if (total !== file.size || offset > total
      || !Number.isSafeInteger(session.chunkBytes) || session.chunkBytes < 1) {
    throw new Error("The file and upload session do not match.");
  }
  onProgress(offset, total);

  while (offset < total) {
    const end = Math.min(offset + session.chunkBytes, total);
    const response = await fetch(url, {
      method: "PATCH",
      headers: {
        ...version,
        "Content-Type": "application/offset+octet-stream",
        "Upload-Offset": String(offset),
        "X-CSRF-TOKEN": csrfToken,
      },
      body: file.slice(offset, end),
    });
    if (response.status !== 204) throw new Error(`Chunk failed (${response.status}).`);
    offset = readNumber(response, "Upload-Offset");
    if (offset !== end) throw new Error("The server returned an unexpected offset.");
    onProgress(offset, total);
  }
}
```

The browser supplies `Content-Length` for the Blob. Preserve it through your proxy. Show an explicit resume action on network failure, and ask the user to start a fresh session after HTTP 410. [tus 1.0 protocol](https://tus.io/protocols/resumable-upload)

Create the session once for the selected file:

```js theme={"theme":{"light":"github-light","dark":"github-dark"}}
const response = await fetch(`/posts/${encodeURIComponent(postId)}/gallery-uploads`, {
  method: "POST",
  headers: {
    "Accept": "application/json",
    "Content-Type": "application/json",
    "X-CSRF-TOKEN": csrfToken,
  },
  body: JSON.stringify({ name: file.name, bytes: file.size }),
});
if (!response.ok) throw new Error(`Cannot start upload (${response.status}).`);

const session = await response.json();
await sendChunks(file, session, csrfToken, updateProgress);
```

Keep `session` while the upload is active. The resume action calls `sendChunks()` again with that session. After it finishes, pass `session.id` to your application's attachment action.

## 5. Inspect and attach a completed local upload

Inspect the fully assembled source with the application's media policy:

```php theme={"theme":{"light":"github-light","dark":"github-dark"}}
use Bjanczak\FilamentFlexFields\Support\Media\Data\MediaPolicy;
use Bjanczak\FilamentFlexFields\Support\Media\Data\MediaWrite;

$staged = $uploads->complete($scope, $sessionId, new MediaWrite(
    policy: new MediaPolicy(
        maxBytes: 256 * 1024 * 1024,
        mimeTypes: ['image/jpeg', 'image/png', 'application/pdf'],
    ),
));
```

The result is a verified temporary source, not a permanent file receipt. Do not pass conversion processors to `complete()`; processing belongs to the final persistence step.

To hand it to an existing FLEX field, resolve the **current** field instance on the server, authorize it again and use the attachment bridge:

```php theme={"theme":{"light":"github-light","dark":"github-dark"}}
use Bjanczak\FilamentFlexFields\Support\FileUpload\Media\UploadAdmission;
use Bjanczak\FilamentFlexFields\Support\FileUpload\Media\Uploads\TemporaryUploadAttachment;

// $field is the current FlexFileUpload instance from your form schema.
$attachment = app(TemporaryUploadAttachment::class)->stage($scope, $sessionId);
app(UploadAdmission::class)->validate($field, $attachment['file']);

// Append for a multiple field; this replaces the current value for a single field.
$state = $field->isMultiple() ? ($field->getRawState() ?? []) : [];
$state[$attachment['fileKey']] = $attachment['file'];
$field->rawState($state)->callAfterStateUpdated();
```

The bridge copies the verified source into Livewire's configured temporary storage without sending it through the browser again. Repeating attachment uses the same reserved temporary identity. The ordinary form save still performs field persistence. The application must also enforce its file-count policy before attachment and apply its normal record-save authorization.

For a Media OS workflow outside a form, open the staged stream and pass it through your authorized [Media OS storage workflow](https://flex-fields.bjanczak.com/docs/media-os-api.md) instead. Close borrowed streams after use. Never publish the private staging path or expose it as a download URL.

## S3 Multipart configuration

For direct uploads to object storage, use the dedicated [S3 Multipart setup](https://flex-fields.bjanczak.com/docs/file-upload-s3.md#direct-uploads-with-s3-multipart). The two transports can share the same session tables.

## Expiration and local cleanup

Enable cleanup explicitly after reviewing its retention policy:

```php theme={"theme":{"light":"github-light","dark":"github-dark"}}
'retention' => ['enabled' => true],
```

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
php artisan fff:uploads:prune --limit=100 --json
```

The command only removes expired private **local** sources belonging to the current root/disk configuration. It preserves sessions marked accepted or completed and reports retryable cleanup work. It does not delete permanent gallery files or S3 objects, install a schedule, or perform record persistence.

To run it regularly, add an application schedule:

```php theme={"theme":{"light":"github-light","dark":"github-dark"}}
use Illuminate\Support\Facades\Schedule;

Schedule::command('fff:uploads:prune --limit=100')
    ->everyTenMinutes()
    ->withoutOverlapping();
```

Retain temporary sources long enough for the application's expected form-save window. For standalone attachment flows, track successful record acceptance in your integration rather than interpreting transfer completion as proof that a record was saved.

## Resume expectations

* Within one transfer, keep the same `File`/`Blob` and ask the server which bytes or parts are already present.
* Across a page reload, the browser may require the user to reselect the source file. File identity and durable client restoration are application responsibilities; matching filename and byte count alone does not prove the same content.
* Server session state survives independently of an open picker, but the default field does not automatically restore a custom chunk uploader after reload.
* A processing worker is a separate stage. Chunking transfers bytes; conversion jobs need their own queue configuration and [processing status presentation](https://flex-fields.bjanczak.com/docs/file-upload-images-and-sources.md).

## Verify your setup

1. Create a session and upload a file larger than one chunk. Confirm that the reported offset advances after each successful request.
2. Interrupt the connection mid-transfer. Resume with the same file and confirm that the next request starts at the offset returned by `HEAD`.
3. Send a deliberately wrong checksum and confirm the offset does not advance. Compare the final file against the source before accepting it.
4. Try the same session from a different account or after revoking record access. The authorizer should deny it.
5. Cancel a temporary upload, then test retention on expired fixtures. Check that active sessions and permanent files are preserved. A verified temporary file can expire while it is still waiting for form acceptance.

For ordinary model storage and gallery relationships, continue with the [gallery recipe](https://flex-fields.bjanczak.com/docs/file-upload-gallery-recipe.md). For photo controls, see the [image editor](https://flex-fields.bjanczak.com/docs/file-upload-image-editor.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.