I am using Express, Node.js, and Mongodb to create the webpage that uploads and displays the image file.
I saved the binary of image in mongodb using schema.
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';
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" }
so it seemed like it's successfully saving the binary data of image file in mogngodb,
but my problem is how to display the image on the webpage now using binary data. How do I convert binary buffer data to create image tag??
<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 :(((
So for storing an image in MongoDB, we need to create a schema with mongoose. For that create the file `model. js` file and define the schema. The important point here is that our data type for the image is a Buffer which allows us to store our image as data in the form of arrays.
There are three ways to store the images in MongoDB: GridFS, Within Document, and Referencing an external URL. If an image or any binary file which is of size less than 16MB can be stored in MongoDB using Binarydata ( bindata ) type.
For example, if we want every document where the value of the name field is more than one value, then what? For such cases, mongoose provides the $in operator. In this article, we will discuss how to use $in operator. We will use the $in method on the kennel collection.
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.
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">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With