当我尝试使用 multer
和 express
上传照片时,一切正常。但是我无法在mongoose
数据库中发送图像名称。
图像已成功上传到upload
目录中。我在正文中得到imageUrl
,但我无法在mongoose
数据库中更新图像名称。但是其他细节已成功更新。
检查下图:
//file upload using multer
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads');
},
filename: function (req, file, callback) {
if (!file.originalname.match(/\.(jpg|png|JPEG)$/)) {
var err = new Error();
err.code = 'filetype';
return callback(err);
} else {
callback(null, Date.now() + file.originalname);
}
}
});
var upload = multer({
storage: storage,
limits: {
fileSize: 1000000
}
}).single('userImage');
app.patch('/updateProfile', authenticate, (req, res) => {
upload(req, res, function(err) {
var body = _.pick(req.body, ['name', 'email', 'mobile', 'imageUrl']);
User.findOneAndUpdate({
_id: req.user._id
}, {
$set: body
}, {
new: true
}).then((user) => {
if (!req.file) {
return res.send({
success: false,
msg: 'No file selected'
})
}
if (!user) {
res.status(404).send({
success: false,
msg: 'user not found'
})
} else {
body.imageUrl = req.file.filename;
console.log(body)
res.send({
sucess: true,
msg: 'update sucessfully',
user
})
}
}).catch((err) => {
res.send({
success: false,
msg: 'something wrong',
error: err
});
});
if (err) {
if (err.code === 'LIMIT_FILE_SIZE') {
return res.send({
success: false,
msg: 'limit file size 1MB '
})
} else if (err.code === 'filetype') {
return res.send({
success: false,
msg: 'Must be valid file extension only jpg or png'
})
} else {
return res.send({
success: false,
msg: 'something went wrong'
})
}
}
});
});
答案 0 :(得分:0)
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './images/post');
},
filename: function (req, file, callback) {
if (!file.originalname.match(/\.(jpg|png|JPEG)$/)) {
var err = new Error();
err.code = 'filetype';
return callback(err);
} else {
callback(null, Date.now() + file.originalname);
}
}
});
var upload = multer({ storage: storage, limits: { fileSize: 1000000 } }).single('imageUrl');
router.post('/posts',authenticate, (req, res) => {
upload(req, res, function (err) {
if (err) {
if (err.code === 'LIMIT_FILE_SIZE') {
return res.send({ success: false, msg: 'limit file size 1MB ' })
} else if (err.code === 'filetype') {
return res.send({ success: false, msg: 'Must be valid file extension only jpg or png' })
} else {
return res.send({ success: false, msg: 'something went wrong' })
}
} else {
if (!req.file) {
return res.send({ success: false, msg: 'No file selected' })
}
var post = new Post({
heading: req.body.heading,
body: req.body.body,
imageUrl: req.file.filename,
creator:req.user.id,
});
post.save().then((result) => {
res.send({ post: result, sucess: true, msg: 'Post created' });
}).catch((err) => {
res.send({ sucess: false, msg: 'post not created', error: err })
});
}
});
});