首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

EasyUI DataGrid 顯示資料庫 BLOB 圖片的正確做法

     編輯:程式設計綜合問答

問題背景

開發者將圖片以 BLOB 型別儲存在 MySQL 資料庫中,嘗試在 EasyUI DataGrid 中直接顯示,但發現無法正常渲染圖片。原始嘗試程式碼存在幾個關鍵問題:

  • PHP 輸出圖片時同時輸出了 HTML 標籤,導致圖片資料被污染
  • DataGrid 的 url 屬性期望回傳 JSON 格式資料,而非圖片二進位流
  • 欄位定義中直接輸出 PHP 變數,而非定義 formatter 渲染函數

正確架構設計

採用「資料介面 + 圖片介面」分離模式:

1. 資料查詢介面 (list.php) - 回傳 JSON

<?php
// list.php
header('Content-Type: application/json; charset=utf-8');

$sql = "SELECT uid, username, pic_id FROM e_user WHERE uid = '1dff5b51f862e6d181577e3ca34248be'";
$result = mysqli_query($conn, $sql);

$rows = array();
while ($row = mysqli_fetch_assoc($result)) {
    // 關鍵:圖片欄位回傳圖片服務的 URL,而非二進位資料
    $row['pic_url'] = "get_image.php?pic_id=" . $row['pic_id'];
    $rows[] = $row;
}

echo json_encode(array('total' => count($rows), 'rows' => $rows));
?>

2. 圖片輸出介面 (get_image.php) - 回傳二進位圖片

<?php
// get_image.php
$pic_id = $_GET['pic_id'];
$sql = "SELECT pic FROM e_user_pic WHERE pic_id = '$pic_id'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);

if ($row && $row['pic']) {
    header("Content-Type: image/png");
    header("Content-Length: " . strlen($row['pic']));
    echo $row['pic'];
} else {
    // 回傳預設佔位圖
    header("Content-Type: image/png");
    readfile('default_avatar.png');
}
?>

3. EasyUI DataGrid 正確配置

<table id="dg" class="easyui-datagrid" url="list.php" method="get" fitColumns="true">
    <thead>
        <tr>
            <th field="username" width="100">用戶名</th>
            <th field="pic_url" width="120" formatter="formatPic">頭像</th>
        </tr>
    </thead>
</table>

<script>
function formatPic(value, row, index) {
    // value 就是 pic_url,直接渲染 img 標籤
    return '<img src="' + value + '" width="80" height="80" style="border-radius:4px;" />';
}
</script>

關鍵點總結

  1. 分離關注點:資料 API 回傳 JSON,圖片 API 回傳二進位流
  2. 使用 formatter:DataGrid 欄位透過 formatter 函數渲染 HTML
  3. 效能考量:大量圖片時建議加上圖片快取策略(ETag、Last-Modified)
  4. 安全性:圖片介面需驗證權限,防止未授權存取

常見誤區

❌ 錯誤:在同一個 PHP 檔案中同時 echo $blob 和 echo '<img...>'
❌ 錯誤:DataGrid url 直接指向輸出圖片的 PHP
✅ 正確:資料與圖片分離,透過 URL 參考關聯

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved