I am trying to upload files from next js app (T3Stack) using formidable backend to upload multiple files inside a file named upload , its actually getting uploaded but I have 2 issues, that I want to upload that file inside upload folder but I am sending an email ( email is just a folder name that I want to create ) I want to check if that email folder created then proceed to upload these files inside that folder with the original name of the file but sadly Formidable is creating a new name that I cannot change here is the frontend code :
const handleFileUpload = async (fileInput) => {
const files = fileInput.target.files;
const formData = new FormData();
for (let i = 0; i < files.length; i++) {
formData.append("multiple-files", files[i]);
}
formData.append("email", user.email);
try {
const res = await fetch("http://localhost:3000/api/files", {body: formData})
if (res.status === 200) {
toast.success("Success");
} else {
toast.error("Failed");
}
} catch (error) {
console.error("Error uploading files:", error);
toast.error("Failed to upload files");
}
};
and here is the backend code :
import { NextApiHandler } from "next";
import formidable from "formidable";
import path from "path";
import { promises as fs } from "fs";
export const config = {
api: {
bodyParser: false,
},
};
const readFile = (req: any): Promise<{ fields: formidable.Fields; files: formidable.Files }> => {
const options: formidable.Options = {};
options.uploadDir = path.join(process.cwd(), "/uploads");
options.maxFileSize = 1024 * 1024; // 1 MB
return new Promise((resolve, reject) => {
const form = formidable(options);
form.parse(req, (err, fields, files) => {
if (err) {
reject(err);
return;
}
resolve({ fields, files });
});
});
};
const handler: NextApiHandler = async (req, res) => {
if(req.method === "POST"){
try {
// Create the 'uploads' folder if it doesn't exist
await fs.mkdir(path.join(process.cwd(), "/uploads"), { recursive: true });
// // Read files from the request
const { fields, files } = await readFile(req);
// Assuming you are handling multiple files, adjust accordingly if needed
const fileDataArray = (files.image || []).map((file) => ({
name: file.originalFilename, // Use the original filename
size: file.size,
path: `/uploads/${fields.email}/${file.newFilename}`,
extension: file.extension,
}));
res.status(200).json({
error: false,
data: fileDataArray.map((fileData) => ({
name: fileData.name,
path: fileData.path,
})),
});
} catch (error) {
console.error("Error processing file upload:", error);
res.status(500).json({ error: true, message: "Internal Server Error" });
}
}
};
export default handler;