以下是用于显示数据库中长图像格式的图像的代码。
upload.php的:
if(isset($_FILES['files'])){
$servername = "localhost";
$username = "root";
$password = "123456";
$dbname = "photost";
$conn=mysqli_connect($servername, $username, $password, $dbname);
$user_id=$_POST['user_id'];
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$errors="";
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
$file_name = $key.$_FILES['files']['name'][$key];
$file_size =$_FILES['files']['size'][$key];
$file_tmp =$_FILES['files']['tmp_name'][$key];
$file_type=$_FILES['files']['type'][$key];
$file_content = file_get_contents($file_tmp);
$maxsize = 10000000;
if($_FILES['files']['tmp_name'][$key]==UPLOAD_ERR_OK) {
if(is_uploaded_file($_FILES['files']['tmp_name'][$key])) {
if( $_FILES['files']['tmp_name'][$key] < $maxsize) {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
if(strpos(finfo_file($finfo, $_FILES['files']['tmp_name'][$key],"image"))==0) {
$imgData = addslashes(file_get_contents($_FILES['files']['tmp_name'][$key]));
$query="INSERT INTO `images`(`id`, `u_id`, `image`, `status`, `file_name`, `file_size`) VALUES ( NULL,'$user_id','{$imgData}',0,'$file_name','$file_type');";
if (mysqli_query($conn, $query)) {
echo "New record created successfully";
} else {
echo "Error: <br>" . mysqli_error($conn);
}
else
echo "<p>Uploaded file is not an image.</p>";
}
}
}
}
}
<body>
<div style="width:100%;height:40%">
</div>
<div align=center>
<form action="" method="POST" enctype="multipart/form-data">
<table style="width:40%">
<tr>
<th align="left">User Id:</th>
<th align="left"><input type='text' name='user_id'></th>
</tr>
<tr>
<th></th>
<th align="left"><input type="file" name="files[]" multiple/></th>
</tr>
<tr>
<th></th>
<th ><input type="submit"/></th>
</tr>
</table>
</form>
</div>
</body>
test.php的:
<body>
<img src="getImage.php?id=1" />
</body>
getImage.php:
<?php
$id = $_GET['id'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "photost";
$conn=mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$query="SELECT * FROM `images` WHERE `id`=$id";
$result =mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$image =$row['image'];
/** check if the image is db */
if($image!=null)
{
$db_img = imagecreatefromstring($image);
Header("Content-type: image/jpeg");
imagejpeg($db_img);
}
mysql_close($conn);
?>
我也试过这个:
$row = mysql_fetch_assoc($result);
header("content-type: image/jpeg");
echo $row['image'];
mysql_close($conn);
我得到像这样的输出
https://i.stack.imgur.com/RDkdM.png
我可以通过从phpmyadmin下载并以jpeg格式保存图像来查看图像。
答案 0 :(得分:-1)
mysqli_fetch_assoc函数返回每行的数组。 现在试试
$image = $row[0]['image'];
代替:
$image = $row['image'];