LiranC
LiranC

Reputation: 2480

Display Images stored in MongoDb in html file

i'm working with Node.js + mongoose + EJS as view engine.

i have managed to make a simple send command that retrieve and send this image on the server side using this guides:

Setup file uploading in an Express.js application using Multer.js

store/display an image in mongodb using mongoose/express

student.findOne({
    'username': req.body.student_username
}, function(err, result) {
    result.img.data = fs.readFileSync(req.file.path);
    result.img.contentType = 'image/png';
    result.save();
    res.contentType(result.img.contentType);
    res.send(result.img.data);
})

however, i am struggling to find a guidance on how i am able to render a page and put images inside an html. i am using EJS view engine. any quick example or tip will be welcomed.

Upvotes: 2

Views: 5366

Answers (1)

user6513442
user6513442

Reputation:

Show picture by student user name:

routes/profile.js:

var userSchema = new Schema({
  username: String,
  img: { data: Buffer, contentType: String }
});
var User = mongoose.model('User', userSchema);

// Get profile picture
router.get('/profile/:userId/picture', function(req,res,next) {
  User.findById( req.params.userId function(err,user) {
      if (err) return next(err);
      res.contentType(user.img.contentType);
      res.send(user.img.data);
  });
});

// Get profile
router.get('/profile/:username', function(req,res,next) {
  User.findOne(
    {'username': req.params.username},
    function(err, result) {
      if (err) return next(err);
      res.render('profile', {
        username: result.username,
        userid: result.id
      });
    });
});

view/profile.ejs:

<html><body>
    <h1><%= username %></h1>
    <img src='/profile/<%= userid %>/picture' />
</body></html>

Upvotes: 2

Related Questions