Skip to content

Instantly share code, notes, and snippets.

@imbharat420
Last active August 29, 2024 18:48
Show Gist options
  • Save imbharat420/2f753e0f1639a4c516a10e66d1609b87 to your computer and use it in GitHub Desktop.
Save imbharat420/2f753e0f1639a4c516a10e66d1609b87 to your computer and use it in GitHub Desktop.
formData in nextjs
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