【问题标题】:I can't upload images using multer and express我无法使用 multer 和 express 上传图片
【发布时间】:2017-03-03 13:29:24
【问题描述】:

我想使用玉形式上传图像然后我想在帖子页面中显示它问题是图像作为没有扩展名的文件上传然后我得到无法读取未定义的属性'mainimage'

我的 app.js 代码如下

var storage = multer.diskStorage({
    destination: function (req, file, callback) {
        callback(null, './public/images/uploads/');
    },
    filename: function (req, file, callback) {
        callback(null, file.fieldname + '-' + Date.now());
    }
});

var upload = multer({storage: storage}).single('mainimage');

然后是我的posts.js

router.post('/add', function(req, res, nect){
    // Get The Form Values
    var title       = req.body.title;
    var category    = req.body.category;
    var body        = req.body.body;
    var author      = req.body.author;
    var date        = new Date();

    if(req.file.mainimage){
        var mainImageOriginalName   = req.file.mainimage.originalname;
        var mainImageName           = req.file.mainimage.name;
        var mainImageMime           = req.file.mainimage.mimetype;
        var mainImagePath           = req.file.mainimage.path;
        var mainImageExt            = req.file.mainimage.extension;
        var mainImageSize           = req.file.mainimage.size;
    } else{
        var mainImageName = 'noimage.png';
    }

    //Form Validation
    req.checkBody('title', 'Title field is required').notEmpty();
    req.checkBody('body', 'Body field is required');

    //Check errors
    var errors = req.validationErrors();
    if(errors){
     res.render('addpost',{
         "errors": errors,
         "title": title,
         "body": body
     });   
    } else{
        var posts = db.get('posts');

        //submit to db
        posts.insert({
            "title": title,
            "body": body,
            "category": category,
            "date": date,
            "author": author,
            "mainimage": mainImageName
        }, function(err, post){
            if(err){
                res.send('There was an issue submitting the post');
            } else{
                req.flash('success', 'Post Submitted');
                res.location('/');
                res.redirect('/');
            }
        });
    }

});

这是我的 posts.jade 表单

form(method='post', action='/posts/add', enctype='multipart/form-data')
        .form-group
            label Title:
            input.form-control(name='title', type='text')
        .form-group
            label Category
            select.form-control(name='category')
                each category, i in categories
                    option(value='#{category.title}') #{category.title}
        .form-group
            label Body
            textarea.form-control(name='body', id='body')
        .form-group
            label Main Image:
            input.form-control(name='mainimage', type='file', id='mainimage')

这里是我想展示的地方

each post, i in posts
            .posts
                h1
                    a(href='/posts/show/#{post._id}')
                        =post.title
                p.meta Posted in #{post.category} by #{post.author} on #{moment(post.date).format('MM-DD-YYYY')}
                img(src='/images/uploads/#{post.mainimage}')
                !=post.body
                a.more(href='/posts/show/#{post._id}') Read More

【问题讨论】:

    标签: javascript node.js express pug multer


    【解决方案1】:

    扩展名问题可能是因为在您的storage 中您命名文件时没有扩展名。

    要添加它,您可以在 storage 方法中插入此代码。

    filename: function (req, file, callback) {
        var extension = file.mimetype;
        extension = extension.substring(extension.indexOf("/")+1, extension.length);
        var filename = file.fieldname + '-' + Date.now() + "." + extension;
        callback(null, filename);
    }
    

    另外,如果您没有映射您的目录,您可以在 app.js 中插入一个静态映射到您保存文件的文件夹,如下所示:

    app.use('/images', express.static(path.join(__dirname, 'images')));
    

    然后,在您的post 页面中,您可以使用http://yourdomain:port/images/<filename.extension> 直接通过其URL 访问下载的文件。

    希望对你有帮助。

    【讨论】:

    • 我试过你告诉我的但仍然给我无法读取未定义的属性'mainimage'
    • 在posts.js 第27 行告诉我错误if(req.file.mainimage){ var mainImageOriginalName = req.file.mainimage.originalname; var mainImageName = req.file.mainimage.name; var mainImageMime = req.file.mainimage.mimetype; var mainImagePath = req.file.mainimage.path; var mainImageExt = req.file.mainimage.extension; var mainImageSize = req.file.mainimage.size; } else{ var mainImageName = 'noimage.png'; }
    • 我没有你的行号,但是在storage 方法之后,在你的post 方法中,你可以从req.body.mainImage 得到这个名字。
    • 我尝试使用 req.body.mainimage 代替它,但它现在告诉我 Cannot read property 'length' of undefined 这行 each category, i in categories option(value='#{category.title}') #{category.title} 这是在我尝试 req.body.mainimage 之前工作
    • 我不知道 JADE 是如何处理这个循环的,但是你必须调试它来准确检查你的 post 对象中的内容,以查看你正在访问的属性是 undefilned
    猜你喜欢
    • 2016-06-14
    • 2018-11-23
    • 2018-10-23
    • 2018-12-16
    • 2021-05-30
    • 2017-02-10
    • 2016-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多