简体   繁体   中英

Display BLOB image from db using JSON

I tried to display my images using JSON but I got

Uncaught SyntaxError: Unexpected end of JSON input

as an error. I tried many things, many ways to solve it, but I failed. I can display text (from a table that has not images (BLOB), I tested it ), but when I try with a table which contains images I got the error.

Here is my code:

PHP - for getting images:

 <?php header("Content-Type: application/json; charset=UTF-8"); //header('Content-Type:image/jpeg'); $obj = json_decode($_GET["x"], false); $conn = new mysqli("localhost", "abu", "aburefko159753", "btt"); $result = $conn->query("SELECT * FROM " . $obj->table . " LIMIT " . $obj->limit); $output = array(); $output = $result->fetch_all(MYSQLI_ASSOC); echo json_encode($output); ?> 

HTML and JS code for display the images:

 <script> var obj, dbParam, xmlhttp; obj = { "table":"bestPlaces", "limit":4 }; dbParam = JSON.stringify(obj); xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("demo").innerHTML = this.responseText; console.log(this.responseText); var myObj = JSON.parse(this.responseText); document.getElementById("demo2").innerHTML = myObj[0].ID; console.log(myObj[0].ID); } }; xmlhttp.open("GET", "getPlaces.php?x=" + dbParam, true); xmlhttp.send(); </script> 
  <p id="test"></p> <p id="test2"></p> 

the same code works fine when I use another table which has not images and the output would be :

[{"ID":"1","name":"test bez session","content":"abu test test"},
 {"ID":"2","name":"test bez session","content":"abu test test"},
 {"ID":"3","name":"test bez session","content":"test test 2"},
 {"ID":"4","name":"test bez session","content":"abu juhu test"}
]

1

But it crash when I use table with images. Any help?

Does console.log(this.responseText); show the full JSON output?

My guess is that you're having trouble with json_encode or JSON.parse on the binary data. Try encoding it in base64 using:

$output['imageCol'] = base64_encode($output['imageCol']);
echo json_encode($output);

where imageCol is the name of the BLOB column and then in JS:

var myObj = JSON.parse(this.responseText);
myObj.imageCol = atob(myObj.imageCol);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM