简体   繁体   English

使用JSON显示数据库中的BLOB图像

[英]Display BLOB image from db using JSON

I tried to display my images using JSON but I got 我尝试使用JSON显示图像,但是我得到了

Uncaught SyntaxError: Unexpected end of JSON input Uncaught SyntaxError:JSON输入意外结束

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. 我可以显示文本(从没有图像的表(BLOB)中进行了测试),但是当我尝试使用包含图像的表时出现错误。

Here is my code: 这是我的代码:

PHP - for getting images: PHP-用于获取图像:

 <?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: 用于显示图像的HTML和JS代码:

 <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 1个

But it crash when I use table with images. 但是当我将表与图像一起使用时会崩溃。 Any help? 有什么帮助吗?

Does console.log(this.responseText); 是否console.log(this.responseText); show the full JSON output? 显示完整的JSON输出?

My guess is that you're having trouble with json_encode or JSON.parse on the binary data. 我的猜测是您在二进制数据上遇到了json_encode或JSON.parse的麻烦。 Try encoding it in base64 using: 尝试使用以下方法在base64中对其进行编码:

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

where imageCol is the name of the BLOB column and then in JS: 其中imageCol是BLOB列的名称,然后是JS:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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