将图像存储在MongoDB中 [英] Store images in MongoDB

查看:347
本文介绍了将图像存储在MongoDB中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用PyMongo连接到我的数据库,当用户上传图像时,我想使用GridFS将其存储在集合中用户特定文档中.我正在这样做:

I'm using PyMongo to connect to my database, when a user uploads an image I want to store it using GridFS within the users specific document in the collection. I'm doing it as so:

class uploadHandler(BaseHandler):

@tornado.web.authenticated

def get(self):

    self.render("upload.html",user=self.current_user)

def post(self):
    db = pymongo.Connection('mongodb://heroku_app.mongolab.com:/heroku_app').heroku_appxxxx
    user = db.userInfo.find_one({'Username':self.current_user})
    file1 = self.request.files['images'][0]
    original_fname = file1['filename']

    print "file: " + original_fname + " is uploaded"

    fs = gridfs.GridFS(user)
    fs.put(file1)
    #db.userInfo.update({'Username':self.current_user},{'$push':{'Images': file1}})  

    self.redirect('/upload')

但这给了我错误:

  Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\tornado\web.py", line 1332, in _execute
    result = method(*self.path_args, **self.path_kwargs)
  File "C:\Users\rsaxs\workspace\pie\src\Server.py", line 4101, in post
    fs = gridfs.GridFS(user)
  File "C:\Python27\lib\site-packages\gridfs\__init__.py", line 53, in __init__
    raise TypeError("database must be an instance of Database")
TypeError: database must be an instance of Database

那么如何最好地将图像存储在mongoDB中集合中特定文档中呢?

How can an image be best stored in a mongoDB in a particular document within a collection then?

推荐答案

使用 GridFS 您可以保存和读取超出BSON文档文件大小限制(16 MB)的文件.它通常用于存储媒体,因为您可以将数据流式传输到客户端.

With GridFS you can save and read files that exceed the BSON document file size limit (16 MB). It is often used to store media since you can stream your data to the client.

GridFS具有特定的文档结构-它实际上由多个文档组成,在将某些内容插入GridFS时只需在db中进行检查即可.由于它具有特殊的结构,并且files可能超过16MB的文档大小限制,因此您不能在其他文档中包含GridFS文档.

GridFS has a specific document structure -- it actually consists of multiple documents, just check it in your db when you insert something to GridFS. Since it has a special structure and files can potentially exceed the 16MB document size limit you cannot include GridFS docs in other documents.

如果要引用某些GridFS对象,则可以通过保存特定GridFS文件的file_id并在需要检索其内容时进行查询来进行查询.

If you want to reference some GridFS objects you can by saving the file_id of the specific GridFS file and querying that when you need to retrieve it's content.

这篇关于将图像存储在MongoDB中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆