2012-10-03 54 views
2

我試圖通過將其轉換爲base64並將其保存到postgresql中的'bytea'字段來將圖像保存在django中。我設法做到了,但字符串是用UTF8編碼的。有沒有一種方法可以將ascii編碼爲該字段?如何使用django在ascii編碼中的postgres bytea字段中保存圖像

這裏是我的自定義Base64編碼模型字段代碼:

import base64 
from django.db import models 

class Base64Field(models.TextField): 

    def contribute_to_class(self, cls, name): 
     if self.db_column is None: 
      self.db_column = name 
     self.field_name = name + '_base64' 
     super(Base64Field, self).contribute_to_class(cls, self.field_name) 
     setattr(cls, name, property(self.get_data, self.set_data)) 

    def get_data(self, obj): 
     #return obj.data_base64 #this works if the image is ascii-encoded 
     return base64.b64decode(getattr(obj, self.field_name)) #this also works well with the setter below 

    def set_data(self, obj, data): 
     setattr(obj, self.field_name, base64.encodestring(data)) #is encoded to UTF8 

    def db_type(self, connection): 
     return 'longtext' 

回答

2

無論bytea場使用text場base64編碼的文字,店的二進制數據。不要將base64編碼的二進制文件存儲在bytea字段中,這只是令人困惑。

我推薦使用byteabytea_output = 'hex'(默認在9.0及以上)。

+0

將二進制文件直接保存到bytea中確實是一個好主意。這個班幫助我做到這一點:https://github.com/niwibe/django-orm-extensions/blob/master/django_orm/postgresql/fields/bytea.py –

相關問題