我有以下 GET 方法的代码,该方法拍摄一张存储在 MySql 中的 blob 类型字段中的照片并返回。我想将它返回到 JSON 字符串内的客户端,其类型可以在 angularjs 应用程序中显示图像。
def GET(self,r):
user_data = CC.get_data(query) # holds the content of the blob field.
print type(user_data) # prints <type 'str'>
data = {'name': 'test',
'photo': user_data}
return json.dump(data)
这给出了,
UnicodeDecodeError: 'utf8' codec can't decode byte 0x89 in position 0:
invalid start byte
我发现在一些网站上最好将照片作为字节数组发送。 我使用 web.py python 框架。 最好的方法是什么?
最佳答案
为了防止数据丢失,发送二进制数据最好的方法是将其编码为 base64
。
import base64
def GET(self,r):
user_data = CC.get_data(query) # holds the content of the blob field.
data = {'name': 'test',
'photo': base64.b64encode(user_data)}
return json.dump(data)
但是,确实不建议通过 JSON 发送二进制数据,特别是在 web 中。例如,您可以发送 URL 来下载照片。
关于python - 将 MySQL blob 内容作为 json 响应发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37464600/