I am trying to change some binary data from my uploaded images to base64 so I can use that to display an image. But the terimal is giving me this error:
TypeError: Cannot read property 'on' of undefined
I don't understand, when I post I also use the .on event and it is working fine. Besides that, I wonder if I am correctly changing the data.
Please take into account that I'm fairly new to node :)
How I save a uploaded image (POST)
// Post to profile page
router.post('/', function(req, res, next) {
var busboy = new Busboy({ headers: req.headers });
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
var conn = mongoose.createConnection('192.168.99.100:32773');
conn.once('open', function () {
var gfs = Grid(conn.db);
var writestream = gfs.createWriteStream({
filename: filename,
content_type: mimetype,
mode: 'w',
metadata: {
belongs_to: req.session.passport.user
}
});
file.pipe(writestream);
writestream.on('close', function(file){
res.render('profile', {
user: req.user,
message: req.flash('uploadMessage', 'Your image has been uploaded successfully!')
})
})
})
})
req.pipe(busboy);
});
Here I try to get a image and convert the binary data to base64 (GET)
// GET to index
router.get('/', function(req, res){
var conn = mongoose.createConnection('192.168.99.100:32773');
conn.once('open', function () {
var gfs = Grid(conn.db);
var readstream = gfs.createReadStream({
filename: 'kittendj.jpg'
});
readstream.pipe();
readstream.on('open', function(chunk){
bufs.push(chunk);
})
readstream.on('close', function(){
var bufs = [];
var fbuf = Buffer.concat(bufs);
var base64 = (fbuf.toString('base64'));
res.render('index', {
isAuthenticated: req.isAuthenticated(),
user: req.user,
imageSrc: '<img src="data:image/jpeg;base64,' + base64 + '">'
})
})
})
});
Resources I checked:
gridfs-stream documentation
Display image in HTML from GridFS
- Display Image in GridFS
- How to retrieve all images from gridFs in a single http Request
- Node.js displaying images from Mongo's GridFS
- nodejs display image stored in gridFS to html