🙌
next.jsのroute handlersからgcsにファイルをupload
概要
next.jsのapp/api/
のapiを利用してgcsにファイルをuploadする。
実装
import { Storage } from '@google-cloud/storage'
import { NextRequest } from 'next/server'
export async function POST(req:NextRequest) {
const requestBody = await req.formData()
const storage = new Storage({
projectId: process.env.PROJECT_ID,
keyFilename: process.env.GOOGLE_APPLICATION_CREDENTIALS,
})
const bucketName = process.env.BUCKET_NAME
const bucket = storage.bucket(bucketName)
const file = requestBody.get('file')
if (file instanceof File) {
const arrayBuffer = await file.arrayBuffer()
const buffer = Buffer.from(arrayBuffer)
await bucket.file(file.name).save(buffer)
}
}
Discussion