I have successfully managed to upload images to my mongoDB using GridFs. Here are some of the images stored in my database:
https://i.sstatic.net/QNdM5.png
fs.files:
https://i.sstatic.net/mDYSz.png
fs.chunks:
https://i.sstatic.net/0K1yJ.png
Provided below is the code I utilized for uploading these 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();
});
The Dilemma:
I am encountering difficulty in reading and displaying these images from mongoDB on the frontend within an HTML <img>
tag.
My attempts so far have only resulted in displaying 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;
});
});
});
The above code snippet was referenced from here
Any assistance would be greatly appreciated as I have been struggling with this issue for quite some time now!