Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

177
Views
Retrieving Images stored in Mongodb with Nodejs

I have small thumbnails stored in a MongoDB collection. While I can extract them with a .findOne() I can not serve them back over an ExpressJS route correctly.

I am not storing thumbs on disk as the heroku environment does not guarantee persisted storage. I am not using GridFS as these are thumbs < 16MB.

Inserting a a new document into the collection goes something like this:

 MongoClient.connect(url, function(err, db){

         var newImg = fs.readFileSync(req.file.path);
         var encImg = newImg.toString('base64');
         var newItem = {
                description: req.body.description, 
                date: Date(), 
                contentType: req.file.mimetype,
                size: req.file.size,
                img: Buffer(encImg)
            };

            db.collection('myimages')
                .insert(newItem, function(err, result){
                    if (err) { console.log(err); }
                });
});

I can serve the img over an Expressjs route like this:

    router.get('/pictures/:picture', function(req, res){
    /* my filename is actually a mdb oid */
    var filename = req.params.picture;
    MongoClient.connect(url, function(err, db){
        db.collection('myimages')
        .findOne({'_id': ObjectId(filename)}, function(err, results){
            console.log(results); //<-- Output below
            res.setHeader('content-type', results.contentType);
            res.send(results.img);     
        });
    });
    });

The nodejs console.log returns an object like this,

    { _id: 58f7ab923b7c842023cf80ec,
      description: '',
      date: 'Wed Apr 19 2017 13:25:22 GMT-0500 (CDT)',
      contentType: 'image/jpeg',
      size: 648436,
      img: 
         Binary {
         _bsontype: 'Binary',
         sub_type: 0,
         position: 864584,
         buffer: <Buffer 2f 39 6a 2f 34 41 41 51 53 6b 5a 4a 52 67 41 42 41 51 41 41 53 41 42 49 41 41 44 2f 34 51 50 38 52 58 68 70 5a 67 41 41 54 55 30 41 4b 67 41 41 41 41 ... > } 
     }

But the browser console gives me an error like this:

Resource interpreted as Document but transferred with MIME type image/jpeg: "http://localhost:3000/picturewall/58f7ab923b7c842023cf80ec".

enter image description here

Am I incorrectly unencoding? Incorrectly setting res headers?

Can someone show me what I'm doing wrong?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

So looks like you save a base64 image in your db.

You do this like this img: Buffer(encImg). In node.js default Buffer encoding is utf8, so your image is saved in db as a base64 utf8 string under binary type in MongoDB!

A proper way will be to specify a buffer encoding when you save your image:

// ...
img: Buffer.from(encImg, 'base64')
// ...

That way when you send a response to client as res.send(results.img.buffer); you'll send binary data instead of a base64 string.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!