I tried to save the image on server directory and saved it's path in mongodb. When client (Angularjs) request details , Express has to send an array of objects in which one object property will send the image and rest of the object properties are data. First i got the image path from mongodb, and read the image from server directory and appended it to the rest of the data and send the response. But the image is sent as buffer array and my html page is not able to display the image buffer array.
Here's code
Express code
var fs = require('fs');
//To view the cars
app.route('/cars/view')
.get(function(req,res){
rentalcars.find().toArray(function(err,docs){
if(err){
res.send([{found:false}]);
}else{
var data = [];
data.push({found:true});
for(var i=0;i<docs.length;i++){
docs[i].imagePath = fs.readFileSync('./assets/images/'+docs[i].imagePath);
data.push(docs[i]);
}
res.send(data);
}
});
});
Client Code
<table>
<tbody ng-repeat="car in home.cars">
<tr>
<img ng-src="data:image/JPEG;base64,{{car.imagePath.data}}">
<td>{{car.carName}}<br/>Segment : {{car.segment}}<br/>Rent : ${{car.rentCost}} /day</td>
</tr>
</tbody>
</table>
Response i get through Express API call is as below
[
{
"found": true
},
{
"_id": "58564aacbd224fdd2b7ad527",
"carName": "sai",
"segment": "suv",
"rentCost": "1000",
"imagePath": {
"type": "Buffer",
"data": [
255,
216,
255,........]
}
}
]
Where data is array of huge data, i didn't paste it completely. How to send the images from Express with Node.js API to Client.
Below is the code that saves the images to the server directory and saves it's path in mongodb.
var filepath ='';
var storage = multer.diskStorage({ //multers disk storage settings
destination: function (req, file, cb) {
cb(null, './assets/images/');
},
filename: function (req, file, cb) {
var datetimestamp = Date.now();
filepath = file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1];
cb(null, filepath);
}
});
var upload = multer({ //multer settings
storage: storage
}).single('file');
//To add new cars
app.route('/cars/add')
.post(function(req,res){
//upload images to server/assets/images/
upload(req,res,function(err){
if(err){
res.json({error_code:1,err_desc:err});
}
var doc = {
carName : req.body.carname,
segment : req.body.segment,
rentCost : req.body.rentcost,
imagePath : filepath
}
rentalcars.insert(doc,function(err,result){
if(err){
res.json({error_code:1,err_desc:err});
}else{
res.json({error_code:0,err_desc:null});
}
});
});
});
ng-srcin Angularjs and fix it like that (fastest to implement and serve, with the least server load) Or 2: load the image in memory and base64 encode it (I do NOT recommend this option)