I am trying to upload multiple image file in node.js using formidable so error is in accessing the path property of fields in formidable
here is my app.js code
app.post('/',(req,res)=>{
const form = formidable({ multiples: true });
form.keepExtensions = true;
form.parse(req, (err, fields, files) => {
if (err) {
return res.status(400).json({
error: "Image could not be uploaded"
});
}
// check for all fields
const {noi} = fields
let user = new User(fields);
console.log(noi)
console.log(files.img[0])
//console.log(files.img.path)
// 1kb = 1000
// 1mb = 1000000
l = noi // noi -> number of images
var i = 0
// to checck the number of image file user want to upload
for(i=0 ; i < l; i++ )
{
if (files.img) {
// console.log("FILES PHOTO: ", files.photo);
user.img[i].data = fs.readFileSync(files.img[i].path);
user.img[i].contentType[i] = files.img[i].type;
}
}
user.save((err, result) => {
if (err) {
return res.status(400).json({
error: errorHandler(err)
});
}
res.json(result);
});
});
})
the output for console.log(files) is :
{
img: [
File {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
size: 7682,
path: 'C:\\Users\\kushw\\AppData\\Local\\Temp\\upload_106d6e0c756a00460b552208b5ac8004.jpeg',
name: 'download.jpeg',
type: 'image/jpeg',
hash: null,
lastModifiedDate: 2021-10-18T14:03:29.718Z,
_writeStream: [WriteStream],
[Symbol(kCapture)]: false
},
File {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
size: 7571,
path: 'C:\\Users\\kushw\\AppData\\Local\\Temp\\upload_be8b426dec71c4ead1cd07ee2f97a03a.jpeg',
name: 'download1.jpeg',
type: 'image/jpeg',
hash: null,
lastModifiedDate: 2021-10-18T14:03:29.721Z,
_writeStream: [WriteStream],
[Symbol(kCapture)]: false
}
]
}
the error I am getting is :
user.img[i].data = fs.readFileSync(files.img[i].path);
^
TypeError: Cannot set property 'data' of undefined
at C:\Users\kushw\Desktop\check\app.js:55:31
at IncomingForm.<anonymous> (C:\Users\kushw\Desktop\check\node_modules\formidable\lib\incoming_form.js:107:9)
at IncomingForm.emit (events.js:315:20)
at IncomingForm._maybeEnd (C:\Users\kushw\Desktop\check\node_modules\formidable\lib\incoming_form.js:557:8)
at C:\Users\kushw\Desktop\check\node_modules\formidable\lib\incoming_form.js:238:12
at C:\Users\kushw\Desktop\check\node_modules\formidable\lib\file.js:79:5
at WriteStream.onfinish (internal/streams/writable.js:689:5)
at WriteStream.emit (events.js:315:20)
at finish (internal/streams/writable.js:657:10)
at finishMaybe (internal/streams/writable.js:644:9)
So what I understood is I need to access the path in img, I tried many ways but not able to read that property.
my model is :
const mongoose = require('mongoose');
const userschema = new mongoose.Schema({
noi: Number,
img:[{
data:Buffer,
type: String
}]
});
module.exports = mongoose.model('User', userschema);
thanks