【发布时间】:2018-08-18 21:55:54
【问题描述】:
我正在尝试使用 multer 将单个图像上传到 mongo,但在尝试访问图像路径时不断收到此错误:
TypeError: Cannot read property 'path' of undefined
at router.post (D:\Workspace\AdminBootstrap\routes\admin_index.js:74:29)
这是我上传图片的代码:
router.post('/add-category', uploads.single('category_image'), (req, res) => {
let title = req.body.title;
console.log('Category Title:\t' + title);
let slug = title.replace(/\s+/g, '-').toLowerCase();
let catImage = req.file.path; // error occurs here
console.log(catImage);
let category = new Category({
title: title,
slug: slug,
image: catImage
});
category.save()
.then(result => {
if (result) {
console.log('Saved Category:\t' + result);
res.redirect('/admin/home');
}
})
.catch(errors => {
console.error('Error Saving Category:\t' + errors);
});
});
这是我的模板:
<label>Upload Image</label>
<input name="category_image" class="form-control" type="file" accept="image/*" id="selImg" onchange="showImage.call(this)">
<img src="#" id="imgPreview" style="display: none; height: 100px; width: 100px">
谁能向我解释一下为什么路径会抛出错误?
【问题讨论】: