我不能用multer和express上传图片

I can't upload images using multer and express

本文关键字:express 不能 multer      更新时间:2023-09-26

我想用玉器形式上传图像然后我想在帖子页面中显示它的问题是图像作为文件上传,没有扩展名,然后我得到无法读取属性'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');

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('/');
            }
        });
    }
});

这是我的帖子。玉形式

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

扩展名问题可能是因为在您的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访问下载的文件。

希望能有所帮助。