将图像存储在Mongodb中可通过Node.js为它们提供服务 [英] Store images in Mongodb serve them with Nodejs
问题描述
我了解Mongodb可以通过两种方式存储图像.
I understand Mongodb can store images in two ways.
- 通过将图像存储为二进制文件在常规文档中
- 通过Gridfs来管理较大的图像.
为简单起见,由于我打算存储的图像很小,因此我将选择选项1.
For simplicity and because the images I plan to server are small, I will go for option 1.
要将图像提供给浏览器,我正在使用nodejs.
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.
推荐答案
我强烈建议不要从MongoDB提供图像.
I would strongly advise against serving images from MongoDB.
最好将它们存储在静态文件存储(S3)中,并且也许将路径保留在MongoDB中.
It would be better to store them on a static filestore (S3) and maybe keep the path in MongoDB.
您可能会使用base64编码将文件放入mongodb: http://www. greywyvern.com/code/php/binary2base64/(或仅仅是base64 shell实用程序).
You would probably use base64 encoding to put the file into mongodb: http://www.greywyvern.com/code/php/binary2base64/ (or just base64 shell utility).
如果仅使用常规文档,则性能成本相对较低(只要缓存良好).如果您使用的是具有GridFS和常规文档的混合数据库,则服务器上将需要大量RAM – GridFS查询的运行方式与文档查询完全不同.
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()})
这篇关于将图像存储在Mongodb中可通过Node.js为它们提供服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!