← back to Dear Bubbe Nextjs

app/api/upload-bubbe/route.ts

48 lines

import { NextRequest, NextResponse } from 'next/server'
import { writeFile } from 'fs/promises'
import { join } from 'path'

export async function POST(request: NextRequest) {
  try {
    const formData = await request.formData()
    const file = formData.get('image') as File

    if (!file) {
      return NextResponse.json(
        { error: 'No file provided' },
        { status: 400 }
      )
    }

    // Validate file type
    if (!file.type.startsWith('image/')) {
      return NextResponse.json(
        { error: 'File must be an image' },
        { status: 400 }
      )
    }

    // Convert file to buffer
    const bytes = await file.arrayBuffer()
    const buffer = Buffer.from(bytes)

    // Save to public/bubbe.png
    const path = join(process.cwd(), 'public', 'bubbe.png')
    await writeFile(path, buffer)

    console.log('[UPLOAD] Bubbe image uploaded successfully:', path)

    return NextResponse.json({
      success: true,
      message: 'Bubbe image uploaded successfully'
    })

  } catch (error) {
    console.error('[UPLOAD] Error uploading Bubbe image:', error)
    return NextResponse.json(
      { error: 'Upload failed: ' + (error as Error).message },
      { status: 500 }
    )
  }
}