Multer-无法读取媒体资源的“路径"的未定义 [英] Multer - Cannot Read Property "path" of Undefined

查看:49
本文介绍了Multer-无法读取媒体资源的“路径"的未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用multer将单个图像上传到mongo,但是在尝试访问图像路径时却不断收到此错误,例如:

I'm trying to upload a single image to mongo using multer but I keep getting this error while trying to access the image path like:

TypeError: Cannot read property 'path' of undefined
at router.post (D:\Workspace\AdminBootstrap\routes\admin_index.js:74:29)

这是我上传图片的代码:

Here's my code to upload the image:

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">

有人可以向我解释为什么路径抛出错误吗?

Can anyone explain to me why the path is throwing an error?

推荐答案

该路径引发错误,因为未在"req"对象内定义文件".它可能在"req.body"对象中定义.使用

The path is throwing an error because "file" is not defined inside "req" object. It is probably defined in "req.body" object. Use

console.log(要求的正文)

console.log(req.body)

确认.由于标题是在"req.body"上定义的,因此"file.path"也应该在同一对象上定义.

to confirm. Since title is defined on "req.body", "file.path" also should be defined on the same object.

这篇关于Multer-无法读取媒体资源的“路径"的未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆