【问题标题】:Display Images stored in MongoDb in html file在 html 文件中显示存储在 MongoDb 中的图像
【发布时间】:2016-10-27 23:18:54
【问题描述】:

我正在使用 Node.js + mongoose + EJS 作为视图引擎。

我已经成功地制作了一个简单的发送命令,使用本指南在服务器端检索和发送此图像:

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

但是,我正在努力寻找有关如何呈现页面并将图像放入 html 的指导。 我正在使用 EJS 视图引擎。 欢迎任何简单的示例或提示。

【问题讨论】:

    标签: javascript node.js mongoose ejs


    【解决方案1】:

    按学生用户名显示图片:

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

    查看/profile.ejs

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-20
      • 2019-10-05
      • 2021-11-27
      • 1970-01-01
      • 1970-01-01
      • 2020-12-19
      • 2020-12-06
      • 2012-12-02
      相关资源
      最近更新 更多