saving picture to mongodb

后端 未结 5 792
花落未央
花落未央 2020-11-30 06:23

am trying yo do this using tornado and pil and mongodb.

avat = self.request.files[\'avatar\'][0][\"body\"]
nomfich = s         


        
相关标签:
5条回答
  • 2020-11-30 06:43

    Try using carierwave-mongoid https://github.com/jnicklas/carrierwave-mongoid I think it is a simple and easy way for you in this case

    0 讨论(0)
  • 2020-11-30 06:46

    You don't necessarily need GridFS for storing files in MongoDB, but it surely makes it a nicer experience, because it handles the splitting and saving of the binary data, while making the metadata also available. You can then store an ID in your User document to the avatar picture.

    That aside, you could also store binary data directly in your documents, though in your code you are not saving the data. You simply are opening it with PIL.Image, but then doing nothing with it.

    Assuming you are using pymongo for your driver, I think what you can do is just wrap the binary data in a Binary container, and then store it. This is untested by me, but I assume it should work:

    from pymongo.binary import Binary
    
    binary_avatar = Binary(avat)
    
    user={
        ...
        "avatar":avatar,
        "avatar_file": binary_avatar
        ...
    }
    

    Now that being said... just make it easier on yourself and use GridFS. That is what it is meant for.

    If you were to use GridFS, it might look like this:

    from gridfs import GridFS
    
    avat_ctype = self.request.files['avatar'][0]["content_type"]
    
    fs = GridFS(db)
    avatar_id = fs.put(avat, content_type=avat_ctype, filename=nomfich)
    
    user={
        ...
        "avatar_name":avatar,
        "avatar_id": avatar_id
        ...
    }
    
    0 讨论(0)
  • 2020-11-30 07:00

    This is the code to insert and retrieve image in mongodb without using gridfs.

    def insert_image(request):
        with open(request.GET["image_name"], "rb") as image_file:
            encoded_string = base64.b64encode(image_file.read())
        print encoded_string
        abc=db.database_name.insert({"image":encoded_string})
        return HttpResponse("inserted")
    
    def retrieve_image(request):
        data = db.database_name.find()
        data1 = json.loads(dumps(data))
        img = data1[0]
        img1 = img['image']
        decode=img1.decode()
        img_tag = '<img alt="sample" src="data:image/png;base64,{0}">'.format(decode)
        return HttpResponse(img_tag)
    
    0 讨论(0)
  • 2020-11-30 07:01

    there is an error in :

              from pymongo.binary import Binary
    

    the correct syntax is:

              from bson.binary import Binary
    

    thk you all for your endless support

    Luca

    0 讨论(0)
  • 2020-11-30 07:05

    You need to save binary data using the Binary() datatype of pymongo.

    http://api.mongodb.org/python/2.0/api/bson/binary.html#module-bson.binary

    0 讨论(0)
提交回复
热议问题