【发布时间】:2022-02-18 06:24:43
【问题描述】:
当用户提交表单并将其插入 mongoDB 服务器时,我正在尝试获取图像。对于图像,我正在使用 Multer 插件,但它向我显示错误。这是我的 NodeJS 代码
const multer = require('multer');
mongoose.connect('mongodb://localhost:27017/mytable',{useNewUrlParser:true} )
.then(()=>
console.log("Mongodb connected"))
.catch(err => console.error("could not connected",err));
const Schema =new mongoose.Schema({
name:String,
email:String,
lastname:String,
pass:String,
phonenumber:String,
zipcode:String,
birthdate:String,
img: {contentType:String,data:Buffer }
});
Schema.plugin(mongoosePaginate)
var user = mongoose.model('mytable', Schema);
//Multer for include image into directory
app.use(multer({ dest: '/public/'}).single('files'));
app.post('/save',(req,res)=>{
console.log("image is" +req.body.img);
var model = new user();
model.name = req.body.name,
model.email=req.body.email,
model.lastname=req.body.lastname,
model.pass=req.body.pass,
model.phonenumber=req.body.phonenumber,
model.zipcode=req.body.zipcode,
model.birthdate=req.body.birthdate,
/* model.img.data = req.body.img, */
model.img.data = fs.readFileSync(req.files.userPhoto.path);
newPic.image.contentType = 'image/png';
model.save(function(err,doc){
});
res.json({result:'sucess'});
res.end();
});
我刚刚上传了所需的代码。我收到 Cannot read property 'userPhoto' of undefined 的错误。我不知道我应该在 fs.readFilesync 中写什么。请帮我将图像插入服务器。
【问题讨论】: