簡體   English   中英

使用JSON顯示數據庫中的BLOB圖像

[英]Display BLOB image from db using JSON

我嘗試使用JSON顯示圖像,但是我得到了

Uncaught SyntaxError:JSON輸入意外結束

作為錯誤。 我嘗試了很多方法,以多種方式來解決它,但失敗了。 我可以顯示文本(從沒有圖像的表(BLOB)中進行了測試),但是當我嘗試使用包含圖像的表時出現錯誤。

這是我的代碼:

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和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> 

當我使用另一個沒有圖像的表時,相同的代碼可以正常工作,輸出為:

[{"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個

但是當我將表與圖像一起使用時會崩潰。 有什么幫助嗎?

是否console.log(this.responseText); 顯示完整的JSON輸出?

我的猜測是您在二進制數據上遇到了json_encode或JSON.parse的麻煩。 嘗試使用以下方法在base64中對其進行編碼:

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

其中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