Saurabh Sharma
Saurabh Sharma

Reputation: 804

Image is not shown from mongodb in ejs template

I am trying to insert an image in mongodb, then I want to fetch and show the image in ejs template.

My code:

index.js

var uploadDir=__dirname+'/uploads';
 var images=Date.now()+'.jpg';
var storage=multer.diskStorage({
    destination:function(request, file, callback){
        callback(null, uploadDir);
        },
        filename:function(request, file, callback){
            console.log(file);
            callback(null, images);
            }
    });
    var upload=multer({storage:storage}).single('photo');

/*============== blog Insert============*/
router.post('/add', upload, function(req, res, next){
    new blogs({
        title: req.body.title,
        description:req.body.description,
        categories:req.body.category,
        img:images,
        date:Date.now()
        }).save(function(err, doc){
             res.send('Inserted');
        });
    });

the Image is successfully inserted into collection as name of file and also storing in disk space. When I try to fetch the image by writing:

<img src="./routes/uploads/<%= blogdata.img%>" />

in my view page the image is absent. I turn to the viewsouce code of that page and its showing the full path i.e

<img src="./routes/uploads/1459772396796.jpg">

Upvotes: 1

Views: 1362

Answers (1)

Jason Livesay
Jason Livesay

Reputation: 6377

Show the code where you define the routes/static file serving for uploads. The relative path doesn't have meaning as a url and normally your URL wouldn't include the routes either so the page source should say /uploads/1459772396796.jpg.

Per your comment you have two static dirs, not sure you can do that, but regardless the path as I said does not include the routes part.

Upvotes: 1

Related Questions