使用express nodejs multer上传文件?

时间:2018-02-10 16:28:09

标签: javascript node.js express pug

我正在尝试使用multer在express中上传文件图像,文件正在目录中上传,但文件名未保存在数据库中。我正在使用mongodb和express。文件名保存为noimage.png。

路由/ posts.js: -

router.post('/add', function(req, res, next) {
  if(req.files.mainimage){
    console.log('Uploading files...');

    // File Info
    var mainImageOriginalName = req.files.mainimage.originalname;
    var mainImageName = req.files.mainimage.name;
    var mainImageMime = req.files.mainimage.mimetype;
    var mainImagePath = req.files.mainimage.path;
    var mainImageExt = req.files.mainimage.extension;
    var mainImageSize = req.files.mainimage.size;
  }
  else{
    var mainImageName = 'noimage.png';
  }
  //console.log(req.files.mainimage.name);

  // Check for errors
  var errors = req.validationErrors();

  if(errors){
    res.render('add', {
        errors: errors,
    });
  }
  else{
    var posts = db.get('posts');

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

1 个答案:

答案 0 :(得分:0)

如果您使用 multer ,似乎您没有指定为multer的规范

router.post('/add', multer({ dest: './uploads/'}).single('myimage'), function(req,res){...})