All checks were successful
Deploy to Production / Build and Deploy (push) Successful in 42s
Next.js bakes public/ at build time — dynamically uploaded files were never served in Docker standalone mode. Store uploads in data/uploads/ and serve via /api/uploads/ with a rewrite for backward compatibility. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
67 lines
2.0 KiB
TypeScript
67 lines
2.0 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server'
|
|
import { writeFile, mkdir } from 'fs/promises'
|
|
import path from 'path'
|
|
import { randomUUID } from 'crypto'
|
|
import { auth } from '@/auth'
|
|
|
|
const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
|
|
const MAX_SIZE = 5 * 1024 * 1024 // 5MB
|
|
|
|
export async function POST(request: NextRequest) {
|
|
try {
|
|
const session = await auth()
|
|
if (!session?.user?.id) {
|
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
|
}
|
|
|
|
const formData = await request.formData()
|
|
const file = formData.get('file') as File
|
|
|
|
if (!file) {
|
|
return NextResponse.json(
|
|
{ error: 'No file uploaded' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
if (!ALLOWED_TYPES.includes(file.type)) {
|
|
return NextResponse.json({ error: 'Invalid file type' }, { status: 400 })
|
|
}
|
|
|
|
if (file.size > MAX_SIZE) {
|
|
return NextResponse.json({ error: 'File too large (max 5MB)' }, { status: 400 })
|
|
}
|
|
|
|
const buffer = Buffer.from(await file.arrayBuffer())
|
|
// Resolve extension from file name, falling back to MIME type (e.g. clipboard pastes)
|
|
let ext = path.extname(file.name).toLowerCase()
|
|
if (!['.jpg', '.jpeg', '.png', '.gif', '.webp'].includes(ext)) {
|
|
const mimeToExt: Record<string, string> = {
|
|
'image/jpeg': '.jpg',
|
|
'image/png': '.png',
|
|
'image/gif': '.gif',
|
|
'image/webp': '.webp',
|
|
}
|
|
ext = mimeToExt[file.type] || '.png'
|
|
}
|
|
const filename = `${randomUUID()}${ext}`
|
|
|
|
// Ensure directory exists (data/uploads is outside public/, served via API route)
|
|
const uploadDir = path.join(process.cwd(), 'data/uploads/notes')
|
|
await mkdir(uploadDir, { recursive: true })
|
|
|
|
const filePath = path.join(uploadDir, filename)
|
|
await writeFile(filePath, buffer)
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
url: `/uploads/notes/${filename}`
|
|
})
|
|
} catch (error) {
|
|
return NextResponse.json(
|
|
{ error: 'Failed to upload file' },
|
|
{ status: 500 }
|
|
)
|
|
}
|
|
}
|