Store images in Mongodb serve them with Nodejs

2020-07-16 08:20发布

问题:

I understand Mongodb can store images in two ways.

  1. in a regular document by storing the image as binary
  2. via Gridfs for managing larger images.

For simplicity and because the images I plan to server are small, I will go for option 1.

To serve the images to a browser I am using nodejs.

My question is how difficult will this be? How do you turn binary data to an actual image a browser will understand? What type of encoding is involved?

Could you point me to tutorials/examples elsewhere on the web?

By the way I know this may not be good idea for performance reasons, I plan to cache the images once served. I just want to avoid the file-system all-together.

回答1:

I would strongly advise against serving images from MongoDB.

It would be better to store them on a static filestore (S3) and maybe keep the path in MongoDB.


You would probably use base64 encoding to put the file into mongodb: http://www.greywyvern.com/code/php/binary2base64/ (or just base64 shell utility).

If you're just using regular documents then the performance cost is relatively low (so long as caching is good). If you're using a mixed database where you have GridFS and regular documents you're going to need a lot of RAM on your server(s) -- the GridFS queries will run completely differently from the document queries.

Converting the image might work like this:

var base64Data = imagefile.replace(/^data:image\/png;base64,/,""),
var dataBuffer = new Buffer(base64Data, 'base64');

// below line won't actually work but it's something along the lines of what you want:

db.foo.insert({magic: 123, etc... img: dataBuffer.toString()})


回答2:

All you need to do to have your web-browser render the content is send the correct headers and response body.

So, assuming you are trying to render a PNG image, your mimetype would be image/png and then add the image files bytes to the response body.

The browser will then interpret this response as being an image of type PNG and render it appropriately