php - 无法从数据库中显示 PHP 中的图像
问题描述
我必须将带有 php 的图像发送到数据库。当我从以下代码发送图像时,图像未显示,如您 在此处看到的
如果我在此处从 phpmyadmin 的插入功能插入图像,图像将正确显示。
请你帮助我好吗?
这是我的代码:
<?php
require_once('connection.php');
if($_SERVER["REQUEST_METHOD"] == "POST") {
$myCreateStatement = "CREATE TABLE Temp (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
Immagine LONGBLOB NULL,
nome VARCHAR(255) NULL,
tipo VARCHAR(255) NULL
)";
$conn->exec($myCreateStatement);
if((!isset($_FILES["file_inviato"])) || ($_FILES["file_inviato"]["error"] != UPLOAD_ERR_OK))
echo "Error";
$tmp_name = $_FILES["file_inviato"]["tmp_name"];
$file_name = $_FILES["file_inviato"]["name"];
$file_type = $_FILES["file_inviato"]["type"];
$dati_file = file_get_contents($tmp_name);
$dati_file = addslashes($dati_file);
$my_Insert_Statement = $conn->prepare("INSERT INTO Temp (id, Immagine, nome, tipo) VALUES (1, :dati_file, :file_name, :file_type)");
$my_Insert_Statement->bindParam(':dati_file', $dati_file);
$my_Insert_Statement->bindParam(':file_name', $file_name);
$my_Insert_Statement->bindParam(':file_type', $file_type);
if ($my_Insert_Statement->execute()) {
echo "Image sent";
} else {
echo "Error";
}
$query = "SELECT * FROM Temp WHERE id = 1";
$stmt = $conn->prepare($query);
$stmt->execute();
$num = $stmt->rowCount();
if ($num) {
$row = $stmt->fetch(PDO::FETCH_ASSOC);
header("Content-type: image/jpeg");
print $row['Immagine'];
exit;
} else {
echo "No image found";
}
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Storage file into DB</title>
</head>
<body>
<p>Select a file</p>
<form name="upload" enctype="multipart/form-data" method="post" action="prova_immagine.php">
<p>
<input type="file" name="file_inviato"><br>
<input type="submit" name="invia" value="Invia file">
</p>
</form>
</body>
</html>
解决方案
这条线
$dati_file = addslashes($dati_file);
不应该是必需的,并且几乎可以肯定会弄乱文件的数据内容。删除它并重试。
编辑
尝试将图像数据输出为 base64 编码图像,例如
echo '<img src="data:image/jpeg;base64,'.base64_encode($row['Immagine']).'"/>';
推荐阅读
- android - java.lang.NoClassDefFoundError: com.google.android.gms.auth.api.signin.GoogleSignInAccount
- django - Django:使用通道的实时数据库
- python-3.x - AttributeError:“Figure”对象在 Flask 中没有属性 savefig
- java - 如何解决 S3 错误:org.jets3t.service.S3ServiceException:S3 GET 失败?爪哇
- mysql - 在连接到远程 mysql(从本地)时出现此错误
- swift - 如何在 StackView 中展开 UITableView?
- python - Python librosa NoBackendError 即使安装了 ffmpeg
- c++ - 尝试访问地图中不存在的密钥时程序崩溃
- go - 在响应正文之前获取状态
- swift - 初始化数组的未知错误原因