从SQL BLOB输出图像


Outputting an image from an SQL BLOB

我有一个php文件,它将图像存储在数据库的BLOB中。上传部分运行良好。然而,它不会显示图像,我不知道为什么。感谢您的帮助。

两个文件:

index.php

<!DOCTYPE HTML>
<html>
<head>
<title>Upload Image</title>
</head>
<body>
<h1>Upload an Image</h1>
<form action="index.php" method="POST" enctype="multipart/form-data">
<label for="image">File:</label>
<input type="file" name="image">
<input type="submit" value="Upload">
</form> 
<?php 
//connect
mysql_connect("localhost", "root","") or die(mysql_error());
mysql_select_db("up") or die(mysql_error());
//file stuff
$file= $_FILES['image']['tmp_name'];
if(!isset($file))  
    echo "Please select an image";
else {
    $image=mysql_real_escape_string(file_get_contents($_FILES['image']['tmp_name']));
    $imageName=mysql_real_escape_string($_FILES['image']['name']);
    $imageSize=getimagesize($_FILES['image']['tmp_name']);
    if(!$imageSize)
        echo "Thats not an image";
    else {
        //upload    
        $query="INSERT INTO store VALUES('','$imageName','$image')";
        $sendQuery=mysql_query($query);
        if(!$sendQuery)
            echo "This is embarressing. It didn't work";
        else {
            $lastid=mysql_insert_id();
            echo "Image was uploaded. <br>Your image:";
            echo "<img src=get.php?id=$lastid/>";   
        }
    }            
}     
?>
</body>
</html>

和get.php:

<?php 
//connect
mysql_connect("localhost", "root","") or die(mysql_error());
mysql_select_db("up") or die(mysql_error());
$id=mysql_real_escape_string($_REQUEST(['id']));
$imageQuery="SELECT * FROM store WHERE id=$id;";
$sendImageQuery=mysql_query($imageQuery);
$image=mysql_fetch_assoc($sendImageQuery);
$image=$image['image'];
header("Content-type: image/jpeg");
echo $image;  
?>

存储在['tmp_name']中的PHP上载是临时文件,当脚本结束/退出时,PHP会自动删除这些文件,除非您已采取措施将其移到其他位置。你需要一些更像的东西

if ($_FILES['image']['error'] != UPLOAD_ERR_OK) {
   ... handle upload ...
   move_uploaded_file($_FILES['image']['tmp_name'], "/path/in/your/document/root/$id.jpg");
} else {
   die("Upload failed with error code: " . $_FILES['image']['error']);
}

首先。请注意添加了错误检查-永远不要假设上传成功。