2

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)

This gives,

UnicodeDecodeError: 'utf8' codec can't decode byte 0x89 in position 0:
invalid start byte

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?

Tiago Martins Peres
  • 14,289
  • 18
  • 86
  • 145
Marlon Abeykoon
  • 11,927
  • 4
  • 54
  • 75

2 Answers2

3

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)

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

augustomen
  • 8,977
  • 3
  • 43
  • 63
  • thanks it worked. But may I know why sending binary data over JSON is not recommended and letting it to download from a URL? – Marlon Abeykoon May 26 '16 at 16:20
  • It greatly depends on your implementation, but to have your client decode a base64 string may be unnecessary, specially because it can download and display images separately, as most browsers do. – augustomen May 26 '16 at 16:35
0

First how to work with blob:

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

To send your image to your template:

def imageResponseView(...) .... return response

bind url to this view

show image using <img src = "//url_to_that_view" />

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

Community
  • 1
  • 1
Destrif
  • 2,104
  • 1
  • 14
  • 22