0

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});
                }
            });
        });

    });
4
  • 2 things: 1. do you save the whole image in the database? 2. If you're using mongoose, can you show me the model? Commented Dec 19, 2016 at 22:51
  • 1. No, i'm saving only the image path in the database and images are saved on the server side directory with help of 'multer'. 2. I'm not using mongoose, i'm using mongodb native driver. And also i have edited my question where i have pasted the code which shows how i'm saving my images on server and it's path in mongodb Commented Dec 20, 2016 at 1:26
  • Since you're using express and you're saving the file location in the database, I recommend to make the route static and use ng-src in 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) Commented Dec 20, 2016 at 1:31
  • I followed your first way of implementation. It's working. Thank you Commented Dec 20, 2016 at 2:06

1 Answer 1

1

Since you're saving the images on disc, you're using express and angular, I recommend using express.static to serve the images and use ng-src to load them the right way.
It's the fastest way to implement and serve with the least server load.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.