简体   繁体   中英

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

I have viewed many similar questions, but I have still not been able to solve my problem.

I have a signup post request, which I am intercepting through passport, but I also need to get the profile photo uploaded, in order to save it to the database.

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

sign up form(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>

I wish to save the image to my MongoDB collection. I have read about Multer and GridFS, but can anybody explain how I should use it?

Pls have a look

What I will suggest you? when user browse image on form, upload this file immediately and get back the image name from server and then fill image field in your form, this is the best solution so you can save only image name into mongodb and then access it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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