# File storage & uploads

> Accept user uploads and serve product media with managed project storage — backed by type checks, size limits, and role-scoped access rules.

- Canonical: https://exaspark.ai/docs/file-storage/

## Why files live in object storage, not your database

Every ExaSpark project comes with managed file storage built right alongside your relational database. Understanding how the two work together keeps your app fast, reliable, and cost-efficient as uploads grow.

Relational databases are engineered for structured rows, searches, and joins — not megabytes of binary image or PDF data. Storing raw files directly inside database columns bloats backups, slows queries across unrelated fields, and wastes memory every time a table loads.

Instead, your app uploads binary files (profile photos, product galleries, receipts, resumes, contracts) to **managed object storage** and saves only lightweight metadata (`storage_key`, `file_name`, `mime_type`, `size_bytes`, `owner_id`) in a database table.

```text
[User Browser]
   |  1. Picks avatar.webp (420 KB) -> client checks type & size
   v
[App Backend]
   |  2. Verifies session, role, MIME type & byte limit
   |  3. Uploads binary to isolated project storage:
   |     avatars/<user_id>/<uuid>.webp
   v
[Cloud Database]
   |  4. Saves metadata row (storage_key, mime_type, size_bytes, visibility)
   |     and updates users.avatar_key
```

## Public assets vs private scoped files

Not every uploaded file should be reachable by anyone with a link. Decide up front whether each upload category is **public** (openly viewable by visitors) or **private** (protected behind server-side session and role checks).

| File category | Visibility | Examples | How access should work |
| --- | --- | --- | --- |
| **Catalog & brand media** | Public | Product photos, hero banners, blog cover images, venue galleries | Served directly via cacheable public URLs for fast page loads |
| **User profile avatars** | Public or Member-only | Account headshots, team icons, public reviewer photos | Public on community sites; member-scoped on private internal portals |
| **Financial & legal docs** | Private (owner + admin) | Payment receipts, tax invoices, signed waivers, wholesale quotes | Server verifies `owner_id` or `admin` role before streaming or signing URL |
| **Personal submissions** | Private (owner + staff) | Job resumes, medical intake PDFs, client briefs, student assignments | Restricted strictly to the uploader and authorized staff roles |

### How private access rules stay safe

Never protect sensitive PDFs or customer receipts merely by using a long random URL in a public bucket. Once a public URL is forwarded, indexed, logged in browser history, or pasted into chat, anyone on the internet can download the document indefinitely.

For private files, require your backend to verify the caller's session and permission rules first (matching `file.owner_id === session.user.id` or `role === 'admin'`). Only after that check passes should the server stream the file or return a short-lived signed download link. See [Authentication & roles](https://exaspark.ai/docs/authentication-and-roles/).

### Preview and Live storage stay isolated

Just like databases and user accounts, **Preview** and **Live** use separate file storage buckets. Uploading test product shots or deleting sample invoices in **Preview** never touches or exposes real customer uploads in **Live**. Read [Preview vs Live isolation](https://exaspark.ai/docs/preview-vs-live/) for the full boundary breakdown.

## Validating uploads before saving

Treat every user upload as untrusted input. Validate files in the browser for instant user feedback, and enforce the exact same rules **on the server** so bypassed forms cannot sneak oversized or malicious files into storage.

### Allowed file types and safe rendering

Specify an explicit allowlist of MIME types and extensions for every upload field rather than accepting "any file."

- **Images (avatars & product galleries).** Allow `image/jpeg`, `image/png`, and `image/webp`. Avoid allowing raw `image/svg+xml` from untrusted users — SVG files can embed executable JavaScript if served inline on your app's domain.
- **Documents (invoices, resumes, forms).** Allow `application/pdf` (and `.docx` or `.csv` only when your workflow truly needs them). Always serve untrusted downloads with a safe `Content-Disposition: attachment` header when downloading.
- **Blocked types.** Reject executable binaries, HTML files, and shell scripts unconditionally on the server.

### Practical file size limits

Setting clear size caps prevents slow mobile uploads, accidental 80 MB camera uploads, and runaway storage bills.

| Upload type | Recommended max size | Processing tip |
| --- | --- | --- |
| **Profile avatar** | 2–5 MB | Resize or display inside a square `object-cover` frame; prefer WebP or JPEG |
| **Product gallery photo** | 5–10 MB | Generate clean hero aspect ratios and lazy-load thumbnails below the fold |
| **PDF receipt, waiver, or resume** | 10–20 MB | Show file name, page/size badge, and a clear upload progress bar |
| **CSV data import** | 5–10 MB | Validate required headers and preview row count before writing to tables |

### Filename hygiene and unique keys

Never save an upload directly under the raw filename a user sends (such as `resume.pdf` or `../../logo.png`). Two users uploading `receipt.pdf` would overwrite each other, and special path characters can break URLs.

Always generate a deterministic, collision-free storage key scoped by resource — for example `receipts/<order_id>/<uuid>.pdf` — while keeping the user's original display label in a separate `original_filename` database column.

## Linking uploads cleanly to database records

Choose between a single column or a dedicated attachments table depending on whether a record owns one file or many.

- **Single file (one-to-one).** Add `avatar_key` on `users` or `cover_image_key` on `posts` when a record always has zero or one image.
- **Galleries & multi-file records (one-to-many).** Create a child table such as `product_images` or `ticket_attachments` with `sort_order`, `alt_text`, and a foreign key pointing to the parent row.

```json
{
  "id": "att_01J9X4K8M2",
  "record_type": "expense_claim",
  "record_id": "exp_4082",
  "owner_id": "usr_912",
  "storage_key": "private/expenses/exp_4082/7f3c9a21.pdf",
  "original_filename": "hotel-receipt-nov.pdf",
  "mime_type": "application/pdf",
  "size_bytes": 284910,
  "visibility": "private",
  "created_at": "2026-11-18T14:22:09Z"
}
```

Follow a clean four-step lifecycle so storage objects and database rows never drift out of sync.

1. **Validate type and size first** — Check extension, MIME type, and maximum byte size in the UI for instant feedback, then re-verify them on the server before accepting the upload.
2. **Upload with a unique scoped key** — Store the binary file under a non-colliding folder path (`public/products/...` or `private/receipts/...`) matching its visibility tier.
3. **Commit the database metadata row** — Save the returned storage key, MIME type, byte size, and owner ID in your table so queries stay fast and auditable.
4. **Clean up replaced or deleted files** — When a user swaps an avatar or an admin deletes a product, delete the old storage object (or mark it for cleanup) so unused files do not accumulate silently.

> **Example prompt (App):** Add two upload flows using managed file storage: (1) Admin product gallery uploads supporting up to 6 public JPEG/PNG/WebP images per product (max 5 MB each, drag-to-reorder via `sort_order`, with alt text); (2) Member receipt uploads on expense claims accepting only PDF or JPEG/PNG up to 10 MB stored privately so only the claim owner and Admins can download them through an authenticated server route. Clean up old files when an attachment is removed.

## Avoiding broken media and leaked documents

Most file bugs surface right after publishing or once real customers start uploading photos from phones. Use this diagnostic table to catch and fix them quickly.

| Symptom | Most common root cause | Reliable fix |
| --- | --- | --- |
| **Broken image icon after Publish** | Seeded Preview image URLs were hard-coded into copy instead of uploaded to Live or bundled as static assets | Bundle brand artwork inside the app or re-upload catalog media through your Live admin panel |
| **Private PDF opens in an incognito browser** | File was saved to a public path with no server-side session check | Move uploads to private storage and serve downloads only through an authenticated, ownership-checked endpoint |
| **Two users overwrite each other's files** | Storage key used the raw user filename (`invoice.pdf`) without a unique ID | Prefix keys with `<entity_id>/<uuid>.<ext>` and store the original name as database metadata |
| **Mobile gallery loads slowly** | Multi-megabyte raw phone photos render at full resolution inside tiny cards | Enforce size limits, serve compressed WebP/JPEG variants, and enable image lazy loading |
| **Orphaned files remain after delete** | Deleting the database row did not remove the underlying object in storage | Delete the storage object inside the same server delete handler right after verifying permissions |

> **Note:** **Need polished catalog images fast?** Generate consistent studio product photos and transparent background cutouts right inside ExaSpark's Creative Studio before uploading them to your storefront. See [Creative Studio media](https://exaspark.ai/docs/media/).

## Next steps

- [Database & data modeling](https://exaspark.ai/docs/accounts-and-data/) — Model clean one-to-many attachment tables linked to your core records.
- [Authentication & roles](https://exaspark.ai/docs/authentication-and-roles/) — Enforce server-side owner and admin checks on every private download.
- [Preview vs Live isolation](https://exaspark.ai/docs/preview-vs-live/) — See how Preview and Live storage buckets stay strictly separated.

## From the blog

- [What is a database?](https://exaspark.ai/blog/what-is-a-database/) — Why structured metadata belongs in tables while binaries live in storage.
- [App security basics](https://exaspark.ai/blog/app-security-checklist/) — Protect private uploads, sessions, and API routes before launch.
- [What is web hosting?](https://exaspark.ai/blog/what-is-web-hosting/) — How servers, storage, and CDNs deliver your app and media fast.
