Route:
router.post('/MOCReport', upload.array('files'), MOCReportController.MOCReport_post);
Controller:
exports.MOCReport_post = (req, res, next) => { const files = req.files;
console.log(files.filename);
if(!files){
const error = new Error('Please upload an image')
error.httpStatusCode = 400
return next (error)
}
var paths = req.files.map(files => file.path)
let newMOCReport = new MOCReport({
facilityName: req.body.facilityName,
MoCDescription: req.body.MoCDescription,
MoCReportDateTime: req.body.MoCReportDateTime,
MoCDisasterLocation: req.body.MoCDisasterLocation,
mocImage: req.files.paths
});
newMOCReport.save().then((MOCReportDoc) => {
res.send(MOCReportDoc);
});
};
Schema:
mocImage:{
type: Array,
required: false
},
Getting Error Undefined when uploading multiple images to mongoDB database with multer.
Error : Listening to port 3000 Connected to MongoDB successfully :)
undefined
POST /MoCReport 500 44.414 ms - 43
CodePudding user response:
Check if you are sending all the files with the same name "files".
You can try to change this:
upload.array('files')
to this:
upload.any()
any()
method will accept all the files. It will not check the name of the field.
Also, after this change, you have to change this line:
var paths = req.files.map(files => file.path);
You have an error there, because you are mapping files
and you are accessing file
. Change it like this:
const paths = req.files.map(file => file.path);
CodePudding user response:
Check this is the complete working code.
const express = require('express')
const app = express()
const port = 3000
const multer = require('multer')
const upload = multer({ dest: 'uploads/' })
app.get('/', (req, res) => {
res.send('<form id="form_el" class=\'new-project\' action=\'/MOCReport\' method=\'POST\' enctype="multipart/form-data">\n'
' <label for=\'file\'>Select your image:</label>\n'
' <input type=\'file\' multiple=\'multiple\' accept=\'image/!*\' name=\'uploadedImages\' id=\'file\' />\n'
' <span class=\'hint\'>Supported files: jpg, jpeg, png.</span>\n'
' <button type=\'submit\'>upload</button>\n'
'</form>')
})
app.post('/MOCReport',upload.any(),function (req, res, next){
const files = req.files;
console.log(JSON.stringify(files));
res.send('Uploaded successfully');
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})