Last active
August 29, 2024 18:48
-
-
Save imbharat420/2f753e0f1639a4c516a10e66d1609b87 to your computer and use it in GitHub Desktop.
formData in nextjs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { NextResponse } from 'next/server'; | |
import fs from 'fs'; | |
import path from 'path'; | |
export async function POST(request) { | |
try { | |
// Parse the form data | |
let form = await request.formData(); | |
const blob = form.get('file'); | |
const filename = form.get('name'); | |
// Validate that filename is not null or undefined | |
if (!filename) { | |
return NextResponse.json({ error: 'Filename is required' }, { status: 400 }); | |
} | |
// Convert blob to buffer | |
const buffer = Buffer.from(await blob.arrayBuffer()); | |
// Define the upload directory path | |
const uploadDir = path.join(process.cwd(), 'public', 'upload'); | |
// Ensure the directory exists, create if it doesn't | |
if (!fs.existsSync(uploadDir)) { | |
fs.mkdirSync(uploadDir, { recursive: true }); | |
} | |
// Set the file path where the file will be saved | |
const filepath = path.join(uploadDir, filename); | |
// Write the file to the specified path | |
fs.writeFileSync(filepath, buffer); | |
// Return a successful response | |
return NextResponse.json({ message: 'File uploaded successfully', filePath: filepath }, { status: 200 }); | |
} catch (error) { | |
console.error('File upload error:', error); | |
return NextResponse.json({ error: 'File upload failed' }, { status: 500 }); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment