如何在nodejs

时间:2018-03-15 10:44:09

标签: node.js mongodb

我需要将用户信息从注册表单保存到mongodb。 除了图像文件,一切都很好。我正在使用Multer将图像从表单上传到服务器。

还要在用户登录后在个人资料页面中显示该图像。

以下是代码:

signup.ejs:

<form action="/signup" method="post" enctype="multipart/form-data">
    <label for>Profile Picture</label>
    <input type="file" name="image"><br><br>
    <label for>Name</label>              
    <input type="text" name="name"><br><br>
    <label for>Email</label>              
    <input type="email" name="email"><br><br>
    <label for>Password</label>  
</form> 

routes.js:

var multer       = require('multer');

var storage = multer.diskStorage({
   destination: function (req, file, cb) {
   cb(null, './uploads');
},
filename: function (req, file, cb) {
   cb(null, file.originalname);
}
});

var upload = multer({ storage: storage });

module.exports = function(app, passport) {

app.post('/signup', upload.single('image'), passport.authenticate('local-signup', {
    successRedirect : '/login', 
    failureRedirect : '/',
    failureFlash : true 
}));

图像上传到/ uploads文件夹。

但是如何获取该图像并将其保存在mongodb中。我使用的是passport.js,下面是保存帖子数据的代码。

UserModel.js:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
  image: { 
      data        : Buffer, 
      contentType : String 
  },
  name: {
      type: String,
  },
  email: {
      type: String,
  },
  password: {
      type: String,
  }
});

passport.js:

passport.use('local-signup', new LocalStrategy({
    usernameField : 'email',
    passwordField : 'password',
    passReqToCallback : true
},
function(req, email, password, done) {
    User.findOne({ 'email' :  email }, function(err, user) {
        if (err) {
            //errorLogger.error(err);
            return done(err);
        }

        if (user) {
            return done(null, false, req.flash('signupMessage', 'Email already exists.'));
        } else {
            var newUser = new User();
            //newUser.image = "dont know how to get image from /uploads" 
              newUser.name = req.body.name;
              newUser.email = req.body.email;
              newUser.password = req.body.password;

              newUser.save(function(err) {
                if (err)
                    throw err;
                return done(null, newUser, req.flash('signupMessage', 'User created'));
            });
        }
});

2 个答案:

答案 0 :(得分:0)

您可以创建自己的中间件来处理上传中间件并获取文件名。

我还建议在上传图片的末尾添加一些随机字符串作为相同名称的保护。

app.post('/signup', middleware , passport.authenticate('local-signup', {
    successRedirect : '/login', 
    failureRedirect : '/',
    failureFlash : true 
}));

中间件

function middleware(req, res, next) {

    var imageName;

    var uploadStorage = multer.diskStorage({
        destination: function (req, file, cb) {
            cb(null, './uploads');
        },
        filename: function (req, file, cb) {
            imageName = file.originalname;
            //imageName += "_randomstring"
            cb(null, imageName);
        }
    });

    var uploader = multer({storage: uploadStorage});

    var uploadFile = upload.single('image');

    uploadFile(req, res, function (err) {
        req.imageName = imageName;
        req.uploadError = err;
        next();
    })
}

你可以使用req.imageName

passport.use('local-signup', new LocalStrategy({
    usernameField : 'email',
    passwordField : 'password',
    passReqToCallback : true
},
function(req, email, password, done) {
    User.findOne({ 'email' :  email }, function(err, user) {
        if (err) {
            //errorLogger.error(err);
            return done(err);
        }

        if (user) {
            return done(null, false, req.flash('signupMessage', 'Email already exists.'));
        } else {
            var newUser = new User();
              newUser.image = req.imageName;
              newUser.name = req.body.name;
              newUser.email = req.body.email;
              newUser.password = req.body.password;

              newUser.save(function(err) {
                if (err)
                    throw err;
                return done(null, newUser, req.flash('signupMessage', 'User created'));
            });
        }
});

答案 1 :(得分:0)

如果您使用的格式为'jpeg / png'的图像且小于16mb,则可以使用此github存储库,它是一个模块,可帮助轻松地将图像保存到mongodb,而无需GRIDFS的复杂性,但是如果文件大于16mb,则需要使用GRIDFS,

这是github存储库中小于16 mb的图像的链接(也可以很好地与react配合使用)

https://github.com/saran-surya/Mongo-Image-Converter