Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a blob with json

I'm trying to create a rest service for my android application where an external database returns items to be stored in the applications local database. I've got everything working except blobs are being returned as null.

this is an example of my jason response.(picture and thumbnail fields are blobs)

{"id":"2","user_id":"1","name":"testing","type":"bouldering","picture":null,"lat":"36","long":"81","alt":"41932","accuracy":"53","thumbnail":null}

Here is my php script to return the data.

<?php
require_once('config.php');

$mysqli = new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
$sql = 'select * from spot_main';
$results =$mysqli->query($sql);

$spots = array();  //array to parse jason from

while($spot = $results->fetch_assoc()){
    $spots[] = $spot;                                                           
}

echo json_encode($spots);
?>

Anyone know of a solution to this problem? I know I'm not doing this the most efficient way(better to store images in the filesystem), but I need this to work.

like image 896
Charlie Jonas Avatar asked Jun 12 '11 16:06

Charlie Jonas


People also ask

How to send Blob data in JSON?

To convert Blob to JSON with the JavaScript File API, we can use the FileReader constructor. For instance, we write: const b = new Blob([JSON. stringify({ "test": "toast" })], { type: "application/json" }) const fr = new FileReader(); fr.

Can you store a Blob in JSON?

You can store JSON data in Oracle Database using columns whose data types are VARCHAR2 , CLOB , or BLOB .

How to get data from JSON Blob?

Retrieving a JSON Blob is accomplished by sending a GET request to /api/jsonBlob/<blobId> , where <blobId> is the last part of the URL path returned from the POST request. Upon successfully retrieving the JSON Blob, a 200 response will be returned.


2 Answers

Encode the binary data as base64 before you generate the JSON.

$obj->picture = base64_encode($binaryData);

You can then decode this in your Android application with any base 64 decoder. Since API level 8 there is a built in util class. Otherwise there are plenty of external libs you can use for targetting Android 2.1 or earlier.

like image 177
David Snabel-Caunt Avatar answered Sep 17 '22 12:09

David Snabel-Caunt


you have to make BLOB to base64_encode

 while($spot = $results->fetch_assoc()){
     $spots[] = $spot;                                                           
    }

Then prepare a foreach loop like this

foreach($spots as $key=>$value){
    $newArrData[$key] =  $spots[$key];
    $newArrData[$key]['picture'] = base64_encode($spots[$key]['picture']);
    $newArrData[$key]['thumbnail'] = base64_encode($spots[$key]['thumbnail']);
}
header('Content-type: application/json');
echo json_encode($newArrData);
like image 33
Sam Arul Raj T Avatar answered Sep 18 '22 12:09

Sam Arul Raj T