简体   繁体   English

如何在nodejs中将上传的图像从multer保存到mongodb

[英]How to save uploaded image from multer to mongodb in nodejs

I need to save user information from a register form to mongodb.我需要将用户信息从注册表单保存到 mongodb。 Everything works well except the image file.除图像文件外,一切正常。 I am using Multer for uploading images from form to server.我正在使用 Multer 将图像从表单上传到服务器。

Also to show that image in the profile page once the user logged in.还可以在用户登录后在个人资料页面中显示该图像。

Below is the code:下面是代码:

signup.ejs:注册.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:路线.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 
}));

The image is uploaded in /uploads folder.图像上传到 /uploads 文件夹中。

But how to get that image and save it in mongodb.但是如何获取该图像并将其保存在 mongodb 中。 I am using passport.js and below is the code for saving post data.我正在使用 passport.js,下面是保存发布数据的代码。

UserModel.js:用户模型.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:护照.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'));
            });
        }
});

You can create your own middleware that will handle the Upload middleware and get the filename.您可以创建自己的中间件来处理上传中间件并获取文件名。

I would also suggest to add some random string at the end of uploaded image as protection from same names.我还建议在上传图片的末尾添加一些随机字符串,以防止重名。

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

middleware中间件

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

and the you can use req.imageName你可以使用 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'));
            });
        }
});

If you are using images of format 'jpeg / png' and if they are less than 16mb, you can go with this github repo, its a module that helps saving images to mongodb easily, and without the complexity of GRIDFS, but in case if your files are greater than 16mb, you need to use GRIDFS,如果您使用的图像格式为“jpeg / png”并且小于 16mb,则可以使用此 github 存储库,它是一个有助于将图像轻松保存到 mongodb 的模块,并且没有 GRIDFS 的复杂性,但以防万一你的文件大于 16mb,你需要使用 GRIDFS,

This is the link for the github repo for images less than 16 mb (and also works well with react)这是 github 存储库的链接,用于小于 16 mb 的图像(也适用于 React)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM