我正在使用 Express、Node.js 和 Mongodb 创建上传和显示图像文件的网页。
我使用模式将图像的二进制文件保存在 mongodb 中。
这是我在 index.js 和 db.js 中的一点代码。
var Post = mongoose.Schema({
image: {data: Buffer, contentType: String}
});
var post= new Post({ });
post.image.data=fs.readFileSync(req.file.path);
post.image.contentType='image/png';
这是我提交图像文件并搜索帖子后的mongo shell部分,以及它的图像字段
"image: {"data:BinData(0,"iVBORw0KGgoAAAANSUhEUE....(I
just cut off the rest of the code.. cuz it was too long)
rkJggg=="),
"contentType" : "image/png" }
看来它已经成功地将图像文件的二进制数据保存在mogngodb中了,
但我的问题是如何使用二进制数据在网页上显示图像。如何转换二进制缓冲区数据以创建图像标签?
<img src= "data:{{image.contentType}};base64,{{image.data}}">
我试过这个,但它给了我一个错误:
Failed to load resource: net::ERR_INVALID_URL
各位大神能告诉我如何解决这个问题吗? 我将非常感谢您的帮助:(((
最佳答案
首先,您必须将缓冲区数据转换为 base64。你可以在后端或前端做到这一点没关系。只需使用 yourBufferData.toString('base64')
。然后就可以使用了。
但是,我建议另一种存储图像的方法,而不是存储二进制数据。假设您使用 nodejs。您可以使用 fs.writeFile
方法在具有该二进制数据的存储库中创建图像。然后您可以将该图像路径存储在记录(db)中。之后,只需将文件路径放入 ng-src="您保存的文件路径"。这是我使用的示例:
var path = 'upload/profiles/' +req.body.userId + '_profile.jpg';
fs.writeFile(path, base64data, function(err) {
if (err) return next(err);
User.findByIdAndUpdate({
_id: req.body.userId
}, {
$set: {
profileImg: 'upload/profiles/' +req.body.userId + '_profile.jpg'
}
}, function(err, user) {
if (err) return next(err);
return res.send(user);
});
});
<img ng-src="savedpath">
关于javascript - 将图像文件存储在 Mongoose 模式中的二进制数据中并以 html 形式显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37077712/