Several file uploads
Upload several files, or several versions of one file, and attach them to a record in one operation.
Result
A user picks an image. The browser uploads the original and a small preview at the same time and attaches both to the record. If the user signs out or cancels, the steps that have not run yet are not sent.
This recipe uses useConvexOperation, an experimental API. For one file per call, useConvexFileUpload is simpler; see Upload files.
Backend
import { ConvexError, v } from 'convex/values'
import type { Id } from './_generated/dataModel'
import { mutation, type MutationCtx } from './_generated/server'
import { auth } from './auth'
import { claimUpload } from './uploads'
async function requireOwnEntry(ctx: MutationCtx, entryId: Id<'entries'>) {
const user = await auth.requireUser(ctx)
const entry = await ctx.db.get(entryId)
// The same error for a missing entry and for an entry of another user.
if (!entry || entry.ownerId !== user.id) {
throw new ConvexError({ code: 'ENTRY_NOT_FOUND' })
}
return { user, entry }
}
export const generateUploadUrl = mutation({
args: { entryId: v.id('entries') },
handler: async (ctx, { entryId }) => {
await requireOwnEntry(ctx, entryId)
return await ctx.storage.generateUploadUrl()
},
})
export const attachImages = mutation({
args: { entryId: v.id('entries'), originalId: v.id('_storage'), previewId: v.id('_storage') },
handler: async (ctx, { entryId, originalId, previewId }) => {
const { user, entry } = await requireOwnEntry(ctx, entryId)
await claimUpload(ctx, user.id, originalId)
await claimUpload(ctx, user.id, previewId)
await ctx.db.patch(entry._id, { originalId, previewId })
},
})Both functions check the user and the entry. attachImages also claims the two storage IDs with claimUpload. It rejects a file that does not exist, is too large, or is already attached to another record. Without this check, a user could attach the private file of another user to their own entry. claimUpload is defined in Upload files.
Page
<script setup lang="ts">
import { useConvexOperation } from '@lupinum/better-convex-nuxt/experimental'
import { api } from '#convex/api'
import type { Id } from '#convex/dataModel'
const props = defineProps<{ entryId: Id<'entries'> }>()
const { run, pending, error, reset } = useConvexOperation(
async (op, entryId: Id<'entries'>, files: Blob[]) => {
const storageIds = await Promise.all(
files.map(async (file) => {
const url = await op.mutation(api.entries.generateUploadUrl, { entryId })
return await op.upload(url, file, { maxSize: 10_000_000 })
}),
)
await op.mutation(api.entries.attachImages, {
entryId,
originalId: storageIds[0]!,
previewId: storageIds[1]!,
})
},
)
async function onPick(event: Event) {
const file = (event.target as HTMLInputElement).files?.[0]
if (!file) return
const preview = await makePreview(file) // your own resize step
await run(props.entryId, [file, preview]).catch(() => undefined)
}
</script>
<template>
<input type="file" accept="image/*" :disabled="pending" @change="onPick" />
<button v-if="pending" @click="reset()">Cancel</button>
<p v-if="error" role="alert">The image could not be uploaded.</p>
</template>run() reads entryId and the files when you call it. A later change of the selection does not change the target.
What the operation does for you
- Every
op.*step runs for the user who started the operation. When that user signs out or another user signs in, later steps reject withIDENTITY_CHANGEDand are not sent. reset()cancels the operation. A running upload is aborted, and later steps reject withCANCELLED.op.upload()checksmaxSizeandallowedTypesbefore it sends the file.
Partial failures
If one upload fails, Promise.all rejects and the attach step does not run. The other file may already be stored. Clean up unattached files with a scheduled Convex function, or call a mutation that deletes them. The library does not know which stored files your application still needs.
Progress per file and a list of "3 of 5 uploaded" stay in your component. Keep one ref per file and update it from the onProgress option of op.upload().