Here's my code to upload and save image in database , when I do this on postman it gives an error of 'undefined' but 'file uploaded successfully' and neither did my image/file is stored in upload folder
//multerfile
const multer = require('multer');
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'originalname');
},
filename: (req, file, cb) => {
cb(null, new Date().toISOString().replace(/:/g, '-') '-' file.originalname);
}
});
const filefilter = (req, file, cb) => {
if (file.mimetype === 'image/png' || file.mimetype === 'image/jpg'
|| file.mimetype === 'image/jpeg'){
cb(null, true);
}else {
cb(null, false);
}
}
const upload = multer({storage: storage, fileFilter: filefilter});
module.exports = {upload}
//imagedata model
const mongoose=require('mongoose');
const imageSchema=new mongoose.Schema({
fileName: {
type: String,
required: true
},
filePath: {
type: String,
required: true
},
fileType: {
type: String,
required: true
},
fileSize: {
type: String,
required: true
}
}, {timestamps: true});
module.exports=mongoose.model('imagedata', imageSchema);
//post controller
exports.uploadimage = async (req, res, next) => {
try{
const file= req.file;
console.log(file);
res.status(201).json({messsage:"file uploaded successfully"})
}catch(error){
res.status(400).send(error.message)
}
CodePudding user response:
u have not specified the destination where u want to save the file create a folder named uploads in ur project and make changes as I have mentioned below:
destination: (req, file, cb) => {
cb(null, 'uploads/originalname');
},