我正在使用 Node.js + mongoose + EJS 作为 View 引擎。
我已经成功制作了一个简单的发送命令,可以使用本指南在服务器端检索和发送此图像:
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 View 引擎。 欢迎任何简单的示例或提示。
最佳答案
按学生用户名显示图片:
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>
关于javascript - 在html文件中显示存储在MongoDb中的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38028613/