从 mongo 数据库中检索图像 [multer express nodejs]
retrieve image from mongo database [multer express nodejs]
似乎有无数关于如何上传的教程,但是none关于检索的教程。
这是我的架构:
var bDataSchema = new mongoose.Schema({
name: String,
img: {
data: Buffer,
contentType: String
}
});
我的设置:
app.use(multer({ storage: storage }).single('photo'));
我已经设法将图像上传到数据库,我想做的是将此数据发送到 ejs 模板,如下所示:
app.get("/b", function(req, res){
bData.find({}, function(err, found){
if(err){
console.log(err);
}else{
res.render("b", {found: found});
}
});
});
然后在我想要的ejs模板上:
<img src="<%=found.img.data%>">
还要提到图像数据路径:public/uploads
所以这里的问题是如何在 img
标签中插入缓冲图像。
为此,您的图片标签必须如下所示:
<img src='data:image/(contentType);base64,(buffer).toString("base64")'>
其中 contentType 可以是 jpeg/gif/png/.../* 并且 buffer 是您的缓冲图像。
在 ejs 中它可能看起来像这样:
<img src="data:image/<%=found.img.contentType%>;base64,<%=found.img.data.toString('base64')%>">
似乎有无数关于如何上传的教程,但是none关于检索的教程。
这是我的架构:
var bDataSchema = new mongoose.Schema({
name: String,
img: {
data: Buffer,
contentType: String
}
});
我的设置:
app.use(multer({ storage: storage }).single('photo'));
我已经设法将图像上传到数据库,我想做的是将此数据发送到 ejs 模板,如下所示:
app.get("/b", function(req, res){
bData.find({}, function(err, found){
if(err){
console.log(err);
}else{
res.render("b", {found: found});
}
});
});
然后在我想要的ejs模板上:
<img src="<%=found.img.data%>">
还要提到图像数据路径:public/uploads
所以这里的问题是如何在 img
标签中插入缓冲图像。
为此,您的图片标签必须如下所示:
<img src='data:image/(contentType);base64,(buffer).toString("base64")'>
其中 contentType 可以是 jpeg/gif/png/.../* 并且 buffer 是您的缓冲图像。
在 ejs 中它可能看起来像这样:
<img src="data:image/<%=found.img.contentType%>;base64,<%=found.img.data.toString('base64')%>">