Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

175
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda