Hello everyone, I want to send Formdata to my database using multer. I logged the data in my route and all data is there, only req.file is undefined, Could that be a problem of multer?
Thanks for your response.
My multer storage:
import multer,{FileFilterCallback} from 'multer'
import { Request } from 'express';
import path from 'path';
import { cwd } from 'process';
type DestinationCallback = (error:Error | null, destination:string)=>void;
type FileNameCallback = (error: Error | null, filename: string) => void;
const maxSize = 100 * 1024 *1024;
const storage = multer.diskStorage({
destination:(req:Request,file:Express.Multer.File,callback:DestinationCallback)=>{
callback(null, path.resolve(process.cwd(), 'admin/public/uploads'))
},
filename: (req:Request, file:Express.Multer.File, callback:FileNameCallback)=>{
callback(null, Date.now()+ "--"+ path.extname(file.originalname))
console.log(file.originalname)
},
})
const upload = multer({
storage:storage,
fileFilter:(req,file,callback)=>{
if(
file.mimetype == "image/png"||
file.mimetype == "image/jpg" ||
file.mimetype == "image/jpeg" ||
file.mimetype == "video/mp4"
){
callback(null, true);
} else{
callback(null,false)
return callback(new Error("Only .png, .jpg, .jpeg, .mp3, .mp4 allowed"))
}
},
limits:{fileSize: maxSize}
});
module.exports = upload;
My route:
productsRouter.post('/',upload.single('image'), verifyTokenAndAdmin, async (req:Request, res:Response)=>{
console.log(req.file)
console.log(req.body.title);
try{
const uploadResult = cloudinary.uploader.upload(req.file!.path,{
upload_preset: "webshop_ts_mern",
resource_type: "auto",
})
const newProducts = new Products({
cloudinary_id: uploadResult.public_id,
title: req.body.title,
producer: req.body.producer,
categories: req.body.categories,
desc: req.body.desc,
price: req.body.price,
currency:req.body.currency,
colors:req.body.colors,
sizes: req.body.sizes,
inStock: req.body.inStock,
image: uploadResult.secure_url,
})
const savedproducts = await newProducts.save();
res.status(200).json(savedproducts);
} catch(error){
res.status(403)
console.log(error);
throw new Error("Action failed");
}
});