从SQL BLOB输出图像

时间:2013-12-13 19:24:57

标签: php mysql sql upload 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;  
?>

1 个答案:

答案 0 :(得分:0)

存储在['tmp_name']中的PHP上传是TEMPORARY文件,当脚本结束/退出时,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']);
}

第一。请注意添加错误检查 - 绝不假设上传成功。