NodeJS expressJS使用multer和passport将文件上传并保存到MongoDB

NodeJS expressJS upload and save file to MongoDB with multer and passport

本文关键字:保存 MongoDB 文件 使用 expressJS multer passport NodeJS      更新时间:2023-09-26

我看过很多类似的问题,但仍然无法解决我的问题。

我有一个注册帖子请求,我正在通过护照拦截,但我也需要上传个人资料照片,以便将其保存到数据库中。

routes.js

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

passport.js

passport.use('local-signup', new LocalStrategy({
  passReqToCallback: true
}, function(req, username, password, done) {
  // logic and add new user
}));

注册表格(html)

<form class="signup-container" action="/signup" method="post">
  <input class="signup-container-input" placeholder="Username"  name="username" />
  <input class="signup-container-input" placeholder="Email ID" name="email" />
  <input class="signup-container-input" type="password" placeholder="Password" name="password" />
  <input class="signup-container-input" type="password" placeholder="Re-enter password" name="reEnterPassword" />
  <input class="signup-container-input" placeholder="Full name" name="name" />
  <div class="signup-container-image">
    <img class="signup-container-image-image" id="profile-photo-img" src="http://www.ivonly.com/assets/images/user-image.jpg" />
    <div class="signup-container-image-uploader">
      <span id="profile-photo-label">Choose photo</span>
      <input class="upload" type="file" name="profilePhoto" id="profile-photo" onchange="getPhoto(this);" />
    </div>
  </div>
  <div class="signup-footer">
    <button type="submit" class="signup-footer-signup">Sign up</button>
    <div class="signup-footer-login">
            Already a user?
      <a href="/login">Login</a>
    </div>
  </div>
</form>

我希望将图像保存到我的MongoDB集合中。我读过关于Multer和GridFS的文章,但有人能解释我应该如何使用它吗?

请看一下

我给你什么建议?当用户浏览表单上的图像时,立即上传该文件,并从服务器获取图像名称,然后在表单中填写图像字段,这是最好的解决方案,因此您可以只将图像名称保存到mongodb中,然后访问它。