first commit
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
'use server'
|
||||
|
||||
import { promises as fs } from 'fs'
|
||||
import path from 'path'
|
||||
import { cookies } from 'next/headers'
|
||||
|
||||
export async function uploadImage(formData: FormData) {
|
||||
const cookieStore = await cookies()
|
||||
const session = cookieStore.get('admin_session')?.value
|
||||
const secret = process.env.ADMIN_SECRET || 'secret'
|
||||
|
||||
if (!session || session !== secret) {
|
||||
throw new Error('Unauthorized')
|
||||
}
|
||||
|
||||
const file = formData.get('file') as File
|
||||
if (!file) {
|
||||
throw new Error('No file uploaded')
|
||||
}
|
||||
|
||||
const bytes = await file.arrayBuffer()
|
||||
const buffer = Buffer.from(bytes)
|
||||
|
||||
const extension = path.extname(file.name) || '.jpg'
|
||||
const filename = `${Date.now()}-${Math.random().toString(36).substring(7)}${extension}`
|
||||
|
||||
const uploadDir = path.join(process.cwd(), 'public', 'uploads')
|
||||
await fs.mkdir(uploadDir, { recursive: true })
|
||||
|
||||
const filePath = path.join(uploadDir, filename)
|
||||
await fs.writeFile(filePath, buffer)
|
||||
|
||||
return { url: `/uploads/${filename}` }
|
||||
}
|
||||
Reference in New Issue
Block a user