while looking for solutions on this topic, i have not been able to find anything directly relating to mongodb, only in relation to multer itself. so, for one of my api routes i wish to have an image upload using multer which has multiple fields, rather than uploading them as an array.
the main function of this api is to grab the image, save the file to the local FS, and then save the filename in mongodb, however i'm unsure on how to handle this filename.
when using code like this, it only returns [Black.jpg] rather than the filename, additionally the image does show up in the FS with the proper name
if possible, i would like to stay away from using .any(), but all of the solutions i have found i have been unable to implement
thanks :))
const storage = multer.diskStorage({
destination: (req, res, cb) => {
cb(null, dir)
},
filename: (req, file, cb) => {
cb(null, Date.now() file.originalname)
}
})
const upload = multer({
storage: storage
})
router.post('/', upload.any(), async (req, res) => {
const business = new Business({
name: req.body.name,
type: req.body.type,
phone: req.body.phone,
address: req.body.address,
coverimg: req.file!==undefined ? req.file.filename : 'Black.jpg',
mainimg: req.file!==undefined ? req.file.filename : 'Black.jpg'
})
try {
const newBusiness = await business.save()
res.status(201).json(newBusiness)
} catch (err) {
res.status(400).json({ message: err.message });
}
})
CodePudding user response:
const storage = multer.diskStorage({
destination: function(req, res, cb){
cb(null, './public/**mention folder name here**')
},
filename: function(req, file, cb){
var ext = file.originalname.split(".").pop();
cb(null, file.fieldname "-" Date.now() "." ext);
}
});
This is how the name of the image appears in local fs:
syntax = field name(sent from frontend)-1673873361364.extention
example =image-1673873361364.jpg
Instead of upload.any() you can use
syntax= upload.single("field name(sent from frontend)")
example=upload.single("single")
CodePudding user response:
yay, i found out that while using upload.fields and accessing it via an array i can finally get the value, here's how :D
const storage = multer.diskStorage({
destination: (req, res, cb) => {
cb(null, dir)
},
filename: (req, file, cb) => {
cb(null, Date.now() file.originalname)
}
})
const upload = multer({
storage: storage
})
var uploadFields = upload.fields([{name: 'coverimg'}, {name: 'mainimg'}])
router.post('/', uploadFields, async (req, res) => {
const business = new Business({
name: req.body.name,
type: req.body.type,
phone: req.body.phone,
address: req.body.address,
coverimg: req.files['coverimg']!==undefined ? req.files['coverimg'][0]['filename'] : 'Black.jpg',
mainimg: req.files['mainimg']!==undefined ? req.files['mainimg'][0]['filename'] : 'Black.jpg'
})
try {
const newBusiness = await business.save()
res.status(201).json(newBusiness)
} catch (err) {
res.status(400).json({ message: err.message });
}
})
cool :p