如何从数据库中检索和显示BLOB图像?

时间:2016-02-09 09:24:50

标签: php mysql

我正在尝试从数据库插入和检索图像。一切顺利,图像以BLOB格式插入到数据库中,但是当我试图检索这些图像时,它不会出现,只有破碎的图标会出现在网页上。代码如下。请帮忙。

ImageUpload.php

<?php
if(count($_FILES) > 0) {
if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
    mysql_connect("localhost", "root", "");
    mysql_select_db ("connection");
    $imgData =addslashes(file_get_contents($_FILES['userImage']['tmp_name']));
    $imageProperties = getimageSize($_FILES['userImage']['tmp_name']);

    $sql = "INSERT INTO output_images(imageType ,imageData)
    VALUES('{$imageProperties['mime']}', '{$imgData}')";
    $current_id = mysql_query($sql) or die("<b>Error:</b> Problem on Image Insert<br/>" . mysql_error());
    if(isset($current_id)) {
        header("Location: listImages.php");
    }
}
}
?>
<HTML>
<HEAD>
<TITLE>Upload Image to MySQL BLOB</TITLE>
<link href="imageStyles.css" rel="stylesheet" type="text/css" />
</HEAD>
<BODY>
<form name="frmImage" enctype="multipart/form-data" action="" method="post" class="frmImageUpload">
<label>Upload Image File:</label><br/>
<input name="userImage" type="file" class="inputFile" />
<input type="submit" value="Submit" class="btnSubmit" />
</form>
</div>
</BODY>
</HTML>

ListImages.php

<?php
    $conn = mysql_connect("localhost", "root", "");
    mysql_select_db("connection");
    $sql = "SELECT imageId FROM output_images ORDER BY imageId DESC"; 
    $result = mysql_query($sql);
?>
<HTML>
<HEAD>
<TITLE>List BLOB Images</TITLE>
<link href="imageStyles.css" rel="stylesheet" type="text/css" />
</HEAD>
<BODY>
<?php
    while($row = mysql_fetch_array($result)) {
    ?>
        <img src="imageView.php?image_id=<?php echo $row["imageId"]; ?>" /><br/>

<?php       
    }
    mysql_close($conn);
?>
</BODY>
</HTML>

imageView.php

<?php
    $conn = mysql_connect("localhost", "root", "");
    mysql_select_db("connection") or die(mysql_error());
    if(isset($_GET['image_id'])) {
        $sql = "SELECT imageType,imageData FROM output_images WHERE imageId=" . $_GET['image_id'];
        $result = mysql_query("$sql") or die("<b>Error:</b> Problem on Retrieving Image BLOB<br/>" . mysql_error());
        $row = mysql_fetch_array($result);
        header("Content-type: " . $row["imageType"]);
        echo $row["imageData"];
    }
    mysql_close($conn);
?>

0 个答案:

没有答案