【发布时间】:2018-09-19 17:23:17
【问题描述】:
我目前正在使用 nodejs 开发 API。我希望用户上传文件以及其他所需的详细信息。但问题是 multer 在我能够验证用户传递的所需详细信息之前上传文件。有没有办法只在 req.body 值验证后才上传文件?
我当前的代码:
router.post("/", upload.single("gallery_item_image"), function (req, res, next) {
Branch
.findById({ _id: req.body.branch_id })
.exec()
.then((doc) => {
if(!doc || req.body.branch_id.length < 24) {
return res.status(404).json({
message: "Invalid Branch ID",
})
}
galleryItem = new GalleryItem({
_id: mongoose.Types.ObjectId(),
branch_id: req.body.branch_id,
caption: req.body.caption,
description: req.body.description,
absoluteImagePath: req.file.path,
imagePath: "some.url"
})
return galleryItem.save()
})
.then((response) => {
console.log(response);
res.status(201).json({
message: "Gallery item successfully added to the database",
galleryItem: {
_id: response._id,
branch_id: response.branch_id,
imagePath: response.imagePath.replace("\\", "/"),
caption: response.caption,
description: response.description,
date: response.date,
absoluteImagePath: response.absoluteImagePath,
meta: {
type: "GET",
url: "some.url",
}
}
})
})
.catch((error) => {
console.log(error);
res.status(500).json({
error: error
})
})
})
【问题讨论】:
标签: javascript node.js express multer