import { NextApiRequest, NextApiResponse } from "next"; import formidable from "formidable"; // Ensure you have installed @types/formidable import fs from "fs"; import path from "path"; // Disable Next.js's default body parsing export const config = { api: { bodyParser: false, }, }; const uploadDir = path.join(process.cwd(), "uploads"); // Define the upload directory // Ensure the upload directory exists if (!fs.existsSync(uploadDir)) { fs.mkdirSync(uploadDir, { recursive: true }); } export default async function handler(req: NextApiRequest, res: NextApiResponse) { const form = new formidable.IncomingForm(); form.uploadDir = uploadDir; // Set the upload directory form.keepExtensions = true; // Keep file extensions form.parse(req, (err, fields, files) => { if (err) { console.error("Error parsing the file:", err); // Log the error return res.status(500).json({ error: "Error parsing the file." }); } const file = files.cv; // Access the uploaded file if (!file) { return res.status(400).json({ error: "No file uploaded." }); } const newFilePath = path.join(uploadDir, file.originalFilename || file.newFilename); // Move the file to the desired location fs.rename(file.filepath, newFilePath, (err) => { if (err) { console.error("Error saving the file:", err); // Log the error return res.status(500).json({ error: "Error saving the file." }); } res.status(200).json({ message: "File uploaded successfully!" }); }); }); }