将 MySQL blob 内容作为 json 响应发送

Posted

技术标签:

【中文标题】将 MySQL blob 内容作为 json 响应发送【英文标题】:Send MySQL blob content as a json response 【发布时间】:2016-09-24 16:17:48 【问题描述】:

我有以下 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 框架。 最好的方法是什么?

【问题讨论】:

【参考方案1】:

为防止数据丢失,发送二进制数据的最佳方法是编码为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.xml 中。例如,您可以发送一个 URL 来下载照片。

【讨论】:

感谢它的工作。但是我可以知道为什么不建议通过 JSON 发送二进制数据并让它从 URL 下载吗? 这在很大程度上取决于您的实现,但是让您的客户端解码 base64 字符串可能是不必要的,特别是因为它可以像大多数浏览器一样单独下载和显示图像。【参考方案2】:

首先如何使用 blob:

http://www.mysqltutorial.org/python-mysql-blob/

要将您的图像发送到您的模板:

def imageResponseView(...) .... 返回响应

将 url 绑定到该视图

使用&lt;img src = "//url_to_that_view" /&gt;显示图片

发件人:I have an image's HTTPResponse. How do I display it in a Django template?

【讨论】:

以上是关于将 MySQL blob 内容作为 json 响应发送的主要内容,如果未能解决你的问题,请参考以下文章

如何将 BLOB 与 JSON 和 PHP 一起使用?

DataFlow 无法读取存储在 Blob 存储中的 API 响应 json 文件

尝试将 MYSQL 的表字段类型从 BLOB 更改为 JSON

UiImage swift 3中的Mysql blob图像显示

您能否将 Blob 存储中的 JSON 文件的全部内容放入 ADF 变量中?如果是这样,怎么做?

我应该在 MySQL 中为 JSON 使用 blob 还是 text?