summaryrefslogtreecommitdiff
path: root/app/api/upload/route.ts
blob: 3b1d8be04fb3b9e3be5689e81b3bc7694102501a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// app/api/upload/route.ts
import { NextRequest, NextResponse } from "next/server"
import { createWriteStream } from "fs"
import path from "path"
import { v4 as uuid } from "uuid"

export async function POST(request: NextRequest) {
  const formData = await request.formData()
  const file = formData.get("file") as File | null
  if (!file) {
    return NextResponse.json({ error: "No file" }, { status: 400 })
  }

  // 여기서는 로컬 /public/uploads 에 저장한다고 가정
  const fileExt = path.extname(file.name)
  const newFileName = `${uuid()}${fileExt}`
  const filePath = path.join(process.cwd(), "public", "uploads", newFileName)

  const arrayBuffer = await file.arrayBuffer()
  const buffer = Buffer.from(arrayBuffer)

  // 로컬에 저장
  await new Promise<void>((resolve, reject) => {
    const writeStream = createWriteStream(filePath)
    writeStream.write(buffer)
    writeStream.end()
    writeStream.on("finish", resolve)
    writeStream.on("error", reject)
  })

  // /uploads/xxxx.ext 로 접근 가능
  const url = `/uploads/${newFileName}`
  return NextResponse.json({
    fileName: file.name,
    url,
    size: file.size,
  })
}