将图像文件存储在mongoose模式的二进制数据中,并以html格式显示图像 [英] Store Image file in Binary data in mongoose schema and Display image in html form
问题描述
我使用Express,Node.js和Mongodb来创建上传并显示图像文件的网页。
I am using Express, Node.js, and Mongodb to create the webpage that uploads and displays the image file.
我使用模式在mongodb中保存了图像的二进制文件。
I saved the binary of image in mongodb using schema.
这是我索引中的一点代码.js和db.js ..
Here is my little bit of code in index.js and 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的一部分,及其图像字段
and here is the part of mongo shell after I submitted image file and searched for post, and its image field
"image: {"data:BinData(0,"iVBORw0KGgoAAAANSUhEUE....(I
just cut off the rest of the code.. cuz it was too long)
rkJggg=="),
"contentType" : "image/png" }
因此它似乎成功保存了mogngodb中图像文件的二进制数据,
so it seemed like it's successfully saving the binary data of image file in mogngodb,
但我的问题是如何使用二进制数据在网页上显示图像。如何转换二进制缓冲区数据以创建图像标记?
<img src= "data:{{image.contentType}};base64,{{image.data}}">
我试过这个,但它给了我一个错误:
I tried this, but it gives me an error:
Failed to load resource: net::ERR_INVALID_URL
<你能告诉我如何解决这个问题吗?
我将非常感谢您的帮助:((
Could you guys please let me know how do I solve this?? I will really appreciate for your help :(((
推荐答案
首先,您必须转换缓冲区数据to base64。你可以在后端或前端完成它没关系。只需使用 yourBufferData.toString('base64')
。然后你可以使用它。
First of all, you have to convert buffer data to base64. You can do it in back-end or front-end it does not matter. Just use yourBufferData.toString('base64')
. Then you can use it.
但是,我建议另一种方法来存储图像而不是存储二进制数据。假设你使用nodejs。你可以使用<$在存储库中使用该二进制数据创建图像c $ c> fs.writeFile 方法。然后你可以将那个图像路径存储在record(db)中。之后,只需将文件路径放入ng-src =你保存的文件路径。以下是我使用的示例:
However, I would suggest another way to store images instead of storing binary data. Assuming you use nodejs. You can create image in a repository with that binary data using fs.writeFile
method. Then you can store that image path in record (db). AFter that, just put the file path into ng-src="file path which you saved". Here is the example which I use:
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">
这篇关于将图像文件存储在mongoose模式的二进制数据中,并以html格式显示图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!