[英]Displaying an image from a Postgresql database in the browser with javascript
I have stored an image in a postgresql database and i have accessed that picture from database with Node.js and displayed it on the browser with我已经在 postgresql 数据库中存储了一张图片,我已经使用 Node.js 从数据库中访问了该图片并将其显示在浏览器上
res.send(`<img src="data:${mimeType};base64,${b64}" />`);
but now i have set up a miniature REST API that only serves that picture but i do not know where to go about it, i have tried sending the whole encoded data like (src = "data:image/png;base64,......)) and then creating an IMG element and making the src of that image with that data. i am in the dark here, any help would be appreciated但现在我已经设置了一个微型 REST API,它只提供该图片,但我不知道去哪里,我尝试发送整个编码数据,如 (src = "data:image/png;base64,... ...)) 然后创建一个 IMG 元素并使用该数据制作该图像的 src。我在这里处于黑暗中,任何帮助将不胜感激
app.get('/', async(req,res) => {
try {
const query = await pool.query("SELECT * FROM picture");
console.log(query.rows)
const buff = query.rows;
const b64 = buff[0].image.toString('base64');
const src = "data:image/png;base64,"+b64;
res.setHeader('Content-type', 'image/png');
res.send(src);
} catch (e) {
console.log(e.message)
}
})
After discussion with a lot of good guys from here, i found the problem.在与这里的很多好人讨论后,我发现了问题。 I did not need to convert image data from the database to base64 format, i can directly serve the image as it's original binary format but have to indicate this header:
我不需要将图像数据从数据库转换为 base64 格式,我可以直接提供图像,因为它是原始二进制格式,但必须指出这个标题:
res.setHeader('Content-type:', 'image/jpg');
and if i need to use that image in my html i just do this:如果我需要在我的 html 中使用该图像,我只需这样做:
<img src="/path to api /" />
Change your route name to /picture
, and after You can directly put the url of your route in your html img tag src like <img src='/picture'>
将您的路线名称更改为
/picture
,然后您可以直接将路线的 url 放在您的 html img 标签 src 中,例如<img src='/picture'>
Replace here the img string with your fetched string from DB: take a look here for working example将此处的 img 字符串替换为从 DB 中获取的字符串: 看看这里的工作示例
app.get("/picture", async (req, res) => {
let img =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAIAAADTED8xAAADMElEQVR4nOzVwQnAIBQFQYXff81RUkQCOyDj1YOPnbXWPmeTRef+/3O/OyBjzh3CD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hf4QtqobAAAAAElFTkSuQmCC";
img = Buffer.from(img.split(",")[1], "base64");
res.writeHead(200, {
"Content-Type": "image/png",
"Content-Length": img.length
});
res.end(img);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.