Reading and displaying images from mongoDB using GridFs

I was able to successfully upload images to mongoDB using GridF. Below are the images from my database:

MongoLab

fs.files:

enter image description here

fs.chunks:

enter image description here

Below is the code I used to upload the images:

var Grid = require('gridfs-stream'); var mongoose = require("mongoose"); Grid.mongo = mongoose.mongo; var gfs = new Grid(mongoose.connection.db); app.post('/picture', function(req, res) { var part = req.files.filefield; var writeStream = gfs.createWriteStream({ filename: part.name, mode: 'w', content_type:part.mimetype }); writeStream.on('close', function() { return res.status(200).send({ message: 'Success' }); }); writeStream.write(part.name); writeStream.end(); }); 

Problem:

I cannot figure out how to read this image from mongoDB and display it on the front side in the HTML <img> .

I have tried this so far , but it only displays the file name:

 app.get('/picture', function(req, res) { gfs.files.find({ filename: 'trooper.jpeg' }).toArray(function (err, files) { if(files.length===0){ return res.status(400).send({ message: 'File not found' }); } res.writeHead(200, {'Content-Type': files[0].contentType}); var readstream = gfs.createReadStream({ filename: files[0].filename }); readstream.on('data', function(chunk) { res.write(chunk); }); readstream.on('end', function() { res.end(); }); readstream.on('error', function (err) { console.log('An error occurred!', err); throw err; }); }); }); 

I took the code above from here

Someone can help. I am stuck on this for DAYS !!!!

+1
javascript mongodb mongoose gridfs gridfs-stream
source share
1 answer

It really should be

 writeStream.write(part.data); 

not

 writeStream.write(part.name); 
+2
source share

All Articles