gpt4 book ai didi

javascript - 无法使用 Multer 获取文件属性

转载 作者:行者123 更新时间:2023-12-03 04:36:38 25 4
gpt4 key购买 nike

我正在尝试使用Multer从我的表单上传图像,当我插入图像时一切正常,但是当没有选择图像时我收到错误。

  • 这是 multer 配置,所有上传的图像都存储在 public/images/uploads 中:
//handle file upload

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

现在我想取回ma​​inImageName的值,但是当我不插入任何图像时,会发生错误无法获取未定义的属性文件名。

  • 这是剩下的:

    //Submit new post
    router.post('/add', upload.single('mainimage'), function(req, res, next) {
    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 && req.file.mainimage){

    var mainImageName = req.file.filename;
    var mainImageMime = req.file.mainimage.mimetype;
    var mainImagePath = req.file.mainimage.path;
    var mainImageSize = req.file.mainimage.size;

    }else{

    //if there was no image uploaded!!
    //noimage.png should be placed in public/images/uploads
    mainImageName = 'noimage.png';
    }

    console.log(mainImageName); //always returns noimage.png !!

    //form validation
    req.checkBody('title', 'You forgot the title').notEmpty();
    req.checkBody('body', 'Please fill in the body').notEmpty();

    //check errors
    var errors = req.validationErrors();

    if(errors){

    var mycategories = []; varcategories = db.get('类别'); categories.find({}, {}, 函数(错误, 类别) {

        for (i=0; i<categories.length; i++) {
    mycategories[i] = categories[i];
    }
    });
    res.render('addpost', {
    'pageTitle': 'Add Post',
    'errors': errors,
    'title': title,
    'body': body,
    'categories': mycategories

    });

    } else{
    var posts = db.get('posts');
    //submit Post
    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_msg', 'Post Submitted');
    res.location('/');
    res.redirect('/');
    }
    });
    }

    });

最佳答案

我发现了问题,条件 if(req.file && req.file.mainimage) 从未满足,因为 req.file.mainimage 始终未定义,所以我只需将其更改为 if(req.file) 即可正常工作。

它应该是这样的:

if(req.file){

var mainImageName = req.file.filename;
var mainImageMime = req.file.mimetype;
var mainImagePath = req.file.path;
var mainImageSize = req.file.size;

}else{

//if there was no image uploaded!!
//noimage.png should be placed in public/images/uploads
mainImageName = 'noimage.png';
}

关于javascript - 无法使用 Multer 获取文件属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43266779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com