首页 > 解决方案 > 如何将缓冲区图像数据从节点 js 发送到 ejs 模板

问题描述

我正在练习使用节点 js 从数据库上传和获取图像。上传部分进行得很顺利,但是获取部分出现了一些问题,获取图片的代码是app.get('/images', async (req, res) => { const img = await image(image is the model with type of buffer).find({}); res.render('image', { img }) }. ejs 模板部分是<% img.forEach(i => { <img src="data:img/png;base64,<%= i.avatar(avatar is property on the image model) %>"> }. 有人可以告诉如何做到这一点?

标签: node.jsejs

解决方案


您可能应该将avatar缓冲区映射base64到 -encoded 字符串并将其传递给 ejs 模板:

app.get('/images', async (req, res) => {
    const img = await image().find({});
    img.avatar = Buffer.from(img.avatar).toString('base64');
    res.render('image', {img});
});

推荐阅读