---
title: "Part 3: accept photos"
description: "Accept photo uploads with size, type and quota checks, strip their metadata, show them, and keep unsafe uploads out with moderation and reports."
canonical_url: "https://nuxt-backend.dev/docs/start/tutorial/uploads"
---
# Part 3: accept photos

> Accept photo uploads with size, type and quota checks, strip their metadata, show them, and keep unsafe uploads out with moderation and reports.

Version: nuxt-backend 0.6.x · Tab: Start · Kind: tutorial · Status: stable

Every page: [llms.txt](https://nuxt-backend.dev/llms.txt) · Skill for coding agents: [nuxt-backend](https://nuxt-backend.dev/.well-known/skills/nuxt-backend/SKILL.md)

Commands use npm; use your project's package manager.

Let people add a photo to a strip, the model draws from it in Part 4, and keep unsafe uploads out.

<table>
<thead>
  <tr>
    <th>
      Part
    </th>
    
    <th>
      You add
    </th>
    
    <th>
      Accounts
    </th>
    
    <th>
      Time
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      3. Accept photos
    </td>
    
    <td>
      Checked photo uploads without location data, a moderation check, and a report button
    </td>
    
    <td>
      An AI gateway
    </td>
    
    <td>
      20 min
    </td>
  </tr>
</tbody>
</table>

## Before you start

You need the app from [Part 2](https://nuxt-backend.dev/docs/start/tutorial/credits). The moderation check calls a model, through the AI SDK. Install it now; Part 4 imports it too:

```bash
npm install ai
```

The calls need a route to the models:

- **A Vercel AI Gateway key** works on every deployment, the anonymous local one from Part 1 included. Create one at [vercel.com](https://vercel.com), put it in `.env.local` as `AI_GATEWAY_API_KEY`, then run `npx nuxt-backend env push`.
- **The Convex AI Gateway** needs no key, but only on a Convex Cloud deployment whose team is on a paid plan, with `@convex-dev/ai-sdk-provider` installed beside `ai`. The anonymous local deployment cannot use it: move to a cloud deployment first with `npx convex login`.

[AI gateway](https://nuxt-backend.dev/docs/services/ai-gateway) compares the two and sets a spending limit. Set one now: Part 4 calls image models.

<steps level="3">

### Accept photos

Convex stores the files. The package adds what Convex leaves to you: it checks the size and the sniffed type after the upload, counts each workspace's files and bytes against a quota, strips EXIF and GPS data from images, and deletes files nobody claims. Set it up in a new file:

```ts [backend/storage.ts]
import { setupStorage } from 'nuxt-backend/storage'
import { components } from './_generated/api'
import type { DataModel } from './_generated/dataModel'
// …
const MB = 1024 * 1024

export const storage = setupStorage<DataModel>(components, {
  maxSize: 8 * MB,
  accept: ['image/jpeg', 'image/png', 'image/webp'],
  quota: { files: 200, bytes: 500 * MB },
  stripMetadata: true,
})
// …
export const { generateUploadUrl, getFileUrl, getShareLink, enableShareLink, revokeShareLink } = storage.api
```

`generateUploadUrl` and `getFileUrl` are what `useUpload`, `<UploadField>` and `<StorageImage>` call. The other three serve the share links of [Part 5](https://nuxt-backend.dev/docs/start/tutorial/notify-and-share), which also fills the gap.

A photo is unclaimed until a mutation of yours keeps it. Claiming checks the file and the quota, and ties the file to its owner, so an export or an erasure finds it. Add the claim to `backend/strips.ts`, with these imports:

```ts [backend/strips.ts]
import { api, internal } from './_generated/api'
import type { Doc } from './_generated/dataModel'
import { internalMutation, internalQuery, type MutationCtx, query, type QueryCtx } from './_generated/server'
import { ai } from './ai'
// …
import { storage } from './storage'
// …
function ownStrip(strip: Doc<'strips'> | null, workspaceId: string): Doc<'strips'> {
  if (strip?.workspaceId !== workspaceId) throw backendError('forbidden', { reason: 'other_workspace' })
  if (strip.hidden) throw backendError('forbidden', { reason: 'hidden' })
  return strip
}
// …
export const checkPhoto = internalQuery({
  args: { id: v.id('strips'), photoId: v.string(), workspaceId: v.string() },
  handler: async (ctx, { id, photoId, workspaceId }) => {
    ownStrip(await ctx.db.get('strips', id), workspaceId)
    if (await storage.fileUrl(ctx, photoId)) throw backendError('invalid_input', { field: 'file', reason: 'upload_claimed' })
  },
})

export const keepPhoto = internalMutation({
  args: { id: v.id('strips'), photoId: v.string(), userId: v.string(), workspaceId: v.string() },
  handler: async (ctx, { id, photoId, userId, workspaceId }) => {
    const strip = ownStrip(await ctx.db.get('strips', id), workspaceId)
    await storage.claim(ctx, photoId, { userId, workspaceId })
    if (strip.photoId) await storage.release(ctx, strip.photoId)
    await ctx.db.patch('strips', id, { photoId })
  },
})
```

The `_generated` imports name everything the finished file uses; Parts 4 and 5 use the rest. `ownStrip` is the check every write to a strip makes: another workspace's strip is `forbidden`, and so is one an administrator hid after a report (below), which takes no new photo and is never drawn. A new photo replaces the old one, and `storage.release` gives the old one back to the package, which deletes it. `checkPhoto` runs the same check before the safety classifier reads a photo, and refuses a file kept already, a strip's photo or a panel, as `upload_claimed`: a check is never paid for a photo that could not be kept.

### Keep uploads safe

Turn on moderation in the scaffold's `backend/ai.ts`. The package runs a safety classifier through your AI gateway. The scaffold already caps what a day of model calls may cost the whole app with `spendLimit`; Panels sets it to 5 dollars:

```ts [backend/ai.ts]
export const ai = setupAi(components, {
  billing,
  rateLimiter,
  moderation: { model: 'meta-llama/llama-guard-4-12b' },
  // …
  spendLimit: { usdPerDay: 5 },
})
```

Past the limit, the `pause_ai` switch turns on until the UTC day ends, and every model call is refused until then. [Part 4](https://nuxt-backend.dev/docs/start/tutorial/generate) fills the gap.

Then add the action the page calls. `storage.acceptUpload` runs the three steps as one call: `checkPhoto`, then `ai.requireSafe` on the photo, then `keepPhoto`. A flagged photo is refused with `invalid_input` and the reason `content_blocked`, so it is never claimed:

```ts [backend/strips.ts]
export const attachPhoto = workspace.action({
  args: { id: v.id('strips'), photoId: v.string() },
  handler: async (ctx, { id, photoId }) => {
    await storage.acceptUpload(ctx, photoId, {
      check: () => ctx.runQuery(internal.strips.checkPhoto, { id, photoId, workspaceId: ctx.workspace.id }),
      safety: ai,
      about: { subject: id },
      keep: () => ctx.runMutation(internal.strips.keepPhoto, {
        id,
        photoId,
        userId: ctx.user.id,
        workspaceId: ctx.workspace.id,
      }),
    })
  },
})
```

When the upload itself is refused, by the classifier or the claim (`invalid_input` for its type or size, `quota_exceeded`), `acceptUpload` deletes it at once instead of leaving it for the daily sweep of unclaimed files, and throws the refusal. A file `checkPhoto` refuses as `upload_claimed` is a kept one, and stays as it is. Any other failure, such as another workspace's strip or a provider that is down, says nothing about the file, so it stays for a retry. `about` names the strip in the record the classifier keeps of a flagged photo.

Moderation misses things, so people need a way to report what slips through. The scaffold's `backend/admin.ts` takes a `reports` option. It says how to describe a strip in the admin console's Reports tab, and how to hide one. `setupAdmin<DataModel>` types the reported row, so checking `table` narrows `id` to a strip's id. The emails a decision sends go through the app's `email`. The two gaps are for Part 5, which empties a hidden strip's presence room:

```ts [backend/admin.ts]
import { setupAdmin } from 'nuxt-backend/admin'
import { components } from './_generated/api'
import type { DataModel } from './_generated/dataModel'
import { email } from './email'
// …
import { routes } from './routes'

export const admin = setupAdmin<DataModel>(components, {
  email,
  reports: {
    describe: async (ctx, { table, id }) => {
      if (table !== 'strips') return null
      const strip = await ctx.db.get('strips', id)
      return strip && { title: strip.idea, url: routes.strip(id), authorId: strip.authorId, files: strip.photoId ? [strip.photoId] : [] }
    },
    hide: async (ctx, { table, id }) => {
      if (table !== 'strips') return
      await ctx.db.patch('strips', id, { hidden: true })
      // …
    },
  },
})

export const {
  listUsers, getUser, listWorkspaces, getWorkspace, getFunnel,
  reportContent, sendNotice, getAppeal, appealDecision,
  getReports, decideReport, flagCrime, decideAppeal,
} = admin.api
```

The exports add the report functions to the scaffold's: `reportContent` behind the report button, `sendNotice` behind the public notice form, `getReports`, `decideReport`, `flagCrime` and `decideAppeal` behind the Reports tab, and `getAppeal` and `appealDecision` for an author who disputes a decision. A hidden strip leaves the list and its page, and `ownStrip` refuses to change it.

### Show the photo and the report button

`<UploadField>` uploads through the base module's `useUploadQueue`, shows progress, and hands the new file to your `:claim` callback. `<StorageImage>` shows it once kept:

```vue [app/components/StripPhoto.vue]
<script setup lang="ts">
import { api } from '#backend/api'
import type { Id } from '#backend/dataModel'

const props = defineProps<{ stripId: Id<'strips'>, photoId?: string }>()
const attach = useAction(api.strips.attachPhoto)
const photo = ref<string | null>(null)
</script>

<template>
  <StorageImage
    v-if="photoId"
    :get-url="api.storage.getFileUrl"
    :storage-id="photoId"
    alt="The photo this strip is drawn from"
    width="320"
  />
  <UploadField
    v-model="photo"
    accept="image/jpeg,image/png,image/webp"
    :claim="id => attach({ id: props.stripId, photoId: id })"
  />
</template>
```

```vue [app/components/ReportStrip.vue]
<script setup lang="ts">
// Moderation misses things: a signed-in reader's quick report reaches the admin
// console's Reports tab. Signed out, the public notice form takes it, with the
// strip and its address in the link, so every shared strip can be reported.
const props = defineProps<{ stripId: string }>()
const report = useReportForm(() => ({ table: 'strips', id: props.stripId }), {
  mode: 'quick',
  url: () => `${useRequestURL().origin}/strips/${props.stripId}`,
  reasons: ['abuse', 'sexual', 'violence', 'spam', 'other'],
})
const { t } = report.labels
</script>

<template>
  <template v-if="!report.isLoading.value">
    <NuxtLink
      v-if="!report.signedIn.value && report.noticePath.value"
      :to="report.noticePath.value"
    >
      Report this strip
    </NuxtLink>
    <form
      v-else
      v-bind="report.bind.root.value"
    >
      <fieldset v-bind="report.bind.reasons.value">
        <legend>{{ t('content.reason') }}</legend>
        <label
          v-for="reason in report.reasons.value"
          :key="reason"
        >
          <input v-bind="report.bind.reason(reason)">
          {{ t(`reasons.${reason}`) }}
        </label>
      </fieldset>
      <div v-bind="report.bind.honeypot.value">
        <input v-bind="report.bind.honeypotInput.value">
      </div>
      <p
        v-if="report.error.value"
        v-bind="report.bind.errorText.value"
      >
        {{ report.labels.errorMessage(report.error.value) }}
      </p>
      <button v-bind="report.bind.submit.value">
        Report this strip
      </button>
      <p v-bind="report.bind.status.value">
        {{ report.announcement.value }}
      </p>
    </form>
  </template>
</template>
```

Put both on the strip's page, under the title:

```vue [app/pages/strips/[id].vue]
<h1>{{ strip.idea }}</h1>
    <StripPhoto
      :strip-id="strip._id"
      :photo-id="strip.photoId"
    />
    <!-- … -->
    <ReportStrip :strip-id="strip._id" />
  </div>
```

**You should see** your photo on the strip's page a moment after you pick it. A file over 8 MB, or one that is not an image, is refused with a message under the field.

</steps>

## Check your work

- Upload a photo taken on a phone, then download it from the strip's page. Its location data is gone.
- Upload a PDF renamed to `.jpg`. The type is sniffed from the bytes, so the field refuses it.
- Signed in, pick a reason under the strip and press **Report this strip**: without one, the form asks for it and sends nothing. Then sign in as an administrator and open `/admin`. The Reports tab lists it. [Run the admin console](https://nuxt-backend.dev/docs/build/auth/admin) makes the first administrator.

Anyone can also report a strip without an account through the packaged `/report` page, the notice form the EU Digital Services Act asks a hosting service for ([Moderate user content](https://nuxt-backend.dev/docs/ship/compliance/moderation)).

## What you used

- `setupStorage` with `maxSize`, `accept`, `quota` and `stripMetadata`, `storage.claim`, `storage.release` and `storage.acceptUpload` ([Accept checked uploads](https://nuxt-backend.dev/docs/build/data/files/checked-uploads)).
- `<UploadField>`, the base module's `useUpload`, and `<StorageImage>` ([Show images](https://nuxt-backend.dev/docs/build/data/files/images)).
- `setupAi({ moderation, spendLimit })` and `ai.requireSafe` ([Keep content safe](https://nuxt-backend.dev/docs/build/ai/content-safety)).
- `reportContent` and `setupAdmin<DataModel>({ reports })` ([Keep content safe](https://nuxt-backend.dev/docs/build/ai/content-safety)).

## Next

[Part 4: generate strips](https://nuxt-backend.dev/docs/start/tutorial/generate) turns an idea and a photo into three panels, paid with credits.


## Sitemap

See the full [sitemap](https://nuxt-backend.dev/sitemap.md) for all pages.
