从mysql读取图像blob并显示它

时间:2016-05-24 18:17:20

标签: php mysql image

我是php,html和mysql的新手,所以道歉我的问题。

我正在将图像上传到mysql(这部分工作正常), 我现在正在尝试阅读它并将其显示在我的页面上。

这是我将其保存到mysql的代码

echo "<br>file selected run script";
echo "<br>file name : ".$_FILES['userfile']['name'];
echo "<br>file type : ".$_FILES['userfile']['type'];
echo "<br>file size : ".$_FILES['userfile']['size'];
$name = $_FILES['userfile']['name'];
$type = $_FILES['userfile']['type'];

$tmpName = $_FILES['userfile']['tmp_name'];
echo "$tmpName";
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);

$sql = "INSERT INTO images (image,name,type)
VALUES ('$data','$name','$type')";
$conn->exec($sql);

它有效。我有一个HTML文件。

和loadimage.php是:

$ id = filter_input(INPUT_GET,“id”,FILTER_SANITIZE_NUMBER_INT);     试试{

    /*** set the PDO error mode to exception ***/
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    /*** The sql statement ***/
    $sql = "SELECT image,type FROM images WHERE id='$id'";
    echo $sql;
            /*** prepare the sql ***/
    $stmt = $conn->prepare($sql);

    /*** exceute the query ***/
    $stmt->execute(); 

    /*** set the fetch mode to associative array ***/
    $stmt->setFetchMode(PDO::FETCH_ASSOC);

    /*** set the header for the image ***/
    $array = $stmt->fetch();

    /*** check we have a single image and type ***/
    if(sizeof($array) == 2)
        {
        /*** set the headers and display the image ***/
        header("Content-type:".$array['type']);

        /*** output the image ***/
        echo $array['image'];
        }
    else
        {
        throw new Exception("Out of bounds Error");
        }
    }
catch(PDOException $e)
    {
    echo $e->getMessage();
    }
catch(Exception $e)
    {
    echo $e->getMessage();
    }
    }

否则         {         echo'请使用真实的身份证号码';         }

它确实连接到mysql,这不是问题。

但Chrome控制台给我的信息是:

资源被解释为文档但使用MIME类型image / jpeg传输:“http://xxxxxxxxxxxxx/loadimage.php?id=12”。

尝试获取我的图像ID 12(所有图像都给出相同的结果....)

1 个答案:

答案 0 :(得分:0)

我理解这一点,当我的代码真正起作用时,我会解决这个问题

相关问题