uploading files locally
Its my first time using T3 stack about a month now and when it comes to upload files to my local server I got stuck for days I used to use multer to upload files but It didn't work for me so I used formidable and it worked but I have alot of issues handling file size to tell user his errors , also to handle specific file for uploads , also when I send the error to the user it keeps also uploading the file even if the user got error please need help on what to do and what is best, should I use formidable or is there anything else that T3 stack specify ? and this is my code just incase someone can tell me what is wrong.
4 Replies
const readFile = (req: any, res: any) => {
const uploadDir = path.join(process.cwd(), "/uploads");
return new Promise((resolve, reject) => {
const customOptions = {
uploadDir: uploadDir,
keepExtensions: true,
allowEmptyFiles: false,
maxFileSize: 5 * 1024 * 1024,
multiples: true,
};
const form = new IncomingForm(customOptions);
const allowedFileTypes = ['image/jpeg', 'image/png', 'application/pdf'];
let errors : string = '';
form.on('file', (name, file) => {
if (!allowedFileTypes.includes(file.mimetype as string)) {
errors = ('Invalid file type. Only PDF and image files are allowed');
}
if (file.size > customOptions.maxFileSize) {
errors = ('File size exceeds the limit (5MB).');
}
});
form.parse(req, (err, fields, files) => {
if (err) {
return res.status(500).json({ error: 'Error parsing form' });
}
const email = fields.email![0];
const emailFolder = path.join(uploadDir, email as string);
if (!fs.existsSync(emailFolder)) {
fs.mkdirSync(emailFolder, { recursive: true });
}
const updatedFiles = files.myfiles?.map((file) => {
const originalFilePath = path.join(emailFolder, file.originalFilename as string);
let counter = 1;
let newFilePath = originalFilePath;
while (fs.existsSync(newFilePath)) {
const fileNameWithoutExt = path.parse(originalFilePath).name;
const fileExt = path.parse(originalFilePath).ext;
newFilePath = path.join(emailFolder,
${fileNameWithoutExt}-${counter}${fileExt});
counter += 1;
}
fs.renameSync(file.filepath, newFilePath);
return { ...file, filepath: newFilePath };
});
if (errors.length > 0) {
return res.json({ errors });
}
resolve({ files: updatedFiles });
});
});
};
you can use zod to validate the file type and file size and dimension and many more.
can I use zod with multer or formidable to handle file validations before upload and send errors to the frontend ?
yes you can use zod validtion in both places so user can't upload file from frontend and also you can use same in backend so if any geek wanna add a file using postman on insomnia it also got same error