从数据库读取图片并显示失败求助:JFIF字符串无法转图片
问题分析与解决方法
你的代码存在两个核心问题导致图片无法正常显示:
- PHP直接输出二进制图片数据,AJAX接收到的是原始二进制字符串,你错误地在JS中使用PHP的
base64_encode函数——这个函数在前端完全不生效。 - JS端错误赋值:把完整的
<img>标签赋值给img1元素的src属性,而src应该是图片的地址或Data URI,而非HTML标签。
解决方法一:PHP返回Base64编码,JS拼接Data URI
修改foto.php:
//file foto.php include './admin/conn.php'; if (!empty($_POST['photo'])) { $Id = $_POST['photo']; // 注意:当前存在SQL注入风险,建议用预处理语句(下文会说明) $query = $conny->query("SELECT image from picture where cf ='$Id'"); if ($row = $query->fetch_array()) { // 将二进制图片转为Base64编码后输出 echo base64_encode($row["image"]); } } else { echo "Errore nell'estrapolazione del dato IN/OUT"; } ?>
修改index.php中的JS代码:
//file index.php $.ajax({ method: 'POST', url: 'foto.php', async: false, data: { photo: data14 }, success: function (result) { if (result != null && result != "") { const imgElement = document.getElementById("img1"); // 拼接Data URI赋值给src imgElement.src = 'data:image/jpeg;base64,' + result; // 单独设置宽高属性 imgElement.width = 150; imgElement.height = 150; } } })
解决方法二:直接通过img的src请求图片(更简单)
这种方法无需AJAX,直接让img元素的src指向foto.php并传参,PHP输出带正确响应头的图片:
修改foto.php:
//file foto.php include './admin/conn.php'; if (!empty($_GET['photo'])) { $Id = $_GET['photo']; // 注意SQL注入风险,建议用预处理语句 $query = $conny->query("SELECT image from picture where cf ='$Id'"); if ($row = $query->fetch_array()) { // 设置图片MIME类型响应头 header('Content-Type: image/jpeg'); echo $row["image"]; exit; // 输出图片后终止脚本 } } else { header('Content-Type: text/plain'); echo "Errore nell'estrapolazione del dato IN/OUT"; } ?>
修改index.php中的JS代码(移除AJAX):
//file index.php const imgElement = document.getElementById("img1"); // 用encodeURIComponent处理参数,避免特殊字符问题 imgElement.src = 'foto.php?photo=' + encodeURIComponent(data14); imgElement.width = 150; imgElement.height = 150;
重要安全提醒:SQL注入风险
当前代码直接将用户输入的$Id拼接到SQL查询中,存在严重的SQL注入漏洞。建议改用预处理语句,示例如下:
// 替换foto.php中的查询部分 $stmt = $conny->prepare("SELECT image from picture where cf = ?"); $stmt->bind_param("s", $Id); // "s"表示参数为字符串类型 $stmt->execute(); $result = $stmt->get_result(); if ($row = $result->fetch_array()) { // 输出Base64或二进制图片 } $stmt->close();
内容的提问来源于stack exchange,提问作者Fab
相关产品推荐
相关产品推荐

