我需要将注册表单中的用户信息保存到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'));
});
}
});