发送MySQL Blob内容作为JSON响应 [英] Send MySQL blob content as a json response

查看:87
本文介绍了发送MySQL Blob内容作为JSON响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个GET方法的以下代码,该方法拍摄一张照片,该照片存储在MySql的blob类型字段中并返回.我想将其返回给JSON字符串中的客户端,其类型应为可以在angularjs应用程序中显示图像.

I have the following code of a GET method which takes a photo which is stored in a blob type field in MySql and return. I want to return it to the client inside a JSON string in a type it can display the image in an angularjs application.

 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框架. 最好的方法是什么?

I have found in some websites its better to send as photo as byte array. Im using web.py python framework. whats the best way to do this?

推荐答案

为防止数据丢失,发送二进制数据最好的方法是将其编码为base64.

To prevent data loss, the best thing you can do to send binary data is encode as 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来下载照片.

However, sending binary data over JSON is really not recommended, specially in web. You can send a URL to download the photo, for example.

这篇关于发送MySQL Blob内容作为JSON响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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