【问题标题】:Multer - Cannot Read Property "path" of UndefinedMulter - 无法读取未定义的属性“路径”
【发布时间】: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">

谁能向我解释一下为什么路径会抛出错误?

【问题讨论】:

    标签: node.js image ejs multer


    【解决方案1】:

    路径抛出错误,因为“文件”未在“req”对象中定义。 它可能在“req.body”对象中定义。使用

    console.log(req.body)

    确认。 由于标题是在“req.body”上定义的,“file.path”也应该在同一个对象上定义。

    【讨论】:

    • 我应该改成req.body.file.path?请详细说明。谢谢
    • 是的,req.body 应该包含 file.path。如果没有,请查看您如何在表单中设置变量。
    • 我已经尝试过 req.body.file.path 但它没有用。这就是你的建议吗?
    • 是的。 console.log(req.body) 的输出是什么?请从 ejs 文件上传代码。
    • 好的。使用图片形式发布时,您必须像设置标题一样设置 file.path 变量,它不会自动设置。
    【解决方案2】:

    在设置您的 HTML 时,您的表单应该有一个属性 enctype="multipart/form-data" 这会将您的文件保存在路径变量中

    【讨论】:

      猜你喜欢
      • 2021-03-24
      • 2018-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-28
      • 2015-11-22
      • 2014-08-16
      • 1970-01-01
      相关资源
      最近更新 更多