CV/my-app/app/api/upload.ts
Ireneusz Bachanowicz c5202ca4c5 Refactor project structure and documentation for CV Optimization Platform
- Updated .cursorrules with clearer project organization
- Removed setup-project.sh script and consolidated project documentation
- Simplified and restructured project rules, overview, and resources
- Added comprehensive task list with detailed development roadmap
- Cleaned up and standardized markdown files in .cursor/rules directory
2025-02-26 00:25:02 +01:00

51 lines
1.8 KiB
TypeScript

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) {
console.log("Received request for file upload"); // Debug log
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) {
console.warn("No file uploaded."); // Warning log
return res.status(400).json({ error: "No file uploaded." });
}
const newFilePath = path.join(uploadDir, file.originalFilename || file.newFilename);
console.log(`Moving file to: ${newFilePath}`); // Debug log
// 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." });
}
console.log("File uploaded successfully!"); // Debug log
res.status(200).json({ message: "File uploaded successfully!" });
});
});
}