Open History to see the last commit
1import * as os from 'node:os'
2import * as path from 'node:path'
3import * as fs from 'node:fs'
4import { createFileRoute } from '@tanstack/react-router'
5import { uploadGeminiFile } from '@tanstack/ai-gemini'
6
7/**
8 * Upload a video (multipart form field `file`) to the Gemini Files API and wait
9 * until it is ACTIVE. Returns `{ uri, mimeType, name }` for the client to pass
10 * back with subsequent chat turns.
11 *
12 * The incoming blob is written to a temp file first — the Files API upload is
13 * most reliable from a path, and it keeps the 24MB body off the heap longer
14 * than necessary.
15 */
16export const Route = createFileRoute('/api/video-understanding-upload')({
17 server: {
18 handlers: {
19 POST: async ({ request }) => {
20 let tmpPath: string | undefined
21 try {
22 const formData = await request.formData()
23 const file = formData.get('file')
24 if (!(file instanceof File)) {
25 return Response.json(
26 { error: 'Expected a `file` field with a video.' },
27 { status: 400 },
28 )
29 }
30
31 const bytes = Buffer.from(await file.arrayBuffer())
32 const safeName = file.name.replace(/[^a-zA-Z0-9._-]/g, '_')
33 tmpPath = path.join(os.tmpdir(), `vu-${process.pid}-${safeName}`)
34 fs.writeFileSync(tmpPath, bytes)
35
36 const uploaded = await uploadGeminiFile(tmpPath, {
37 mimeType: file.type || 'video/mp4',
38 })
39
40 console.log(`>> video-understanding upload -> ${uploaded.uri}`)
41 return Response.json(uploaded)
42 } catch (error: any) {
43 console.error(
44 '[API Route] video-understanding upload error:',
45 error?.message,
46 )
47 return Response.json(
48 { error: error?.message ?? 'Upload failed' },
49 { status: 500 },
50 )
51 } finally {
52 if (tmpPath) {
53 try {
54 fs.unlinkSync(tmpPath)
55 } catch {
56 // best-effort cleanup
57 }
58 }
59 }
60 },
61 },
62 },
63})