douyi3676 2013-03-16 17:34
浏览 66
已采纳

使用php和显示将图像存储到mysql DB中

Having big time problems in displaying an image out of my mysql database

I'm storing it in a longblob type

when the image is displayed i get a broken image icon

here is code for storing image

if(isset($_FILES['image']) && $_FILES['image']['size'] > 0 && isset($_POST['photoName']))
{
    //temporary file name
    // Temporary file name stored on the server
    $tmpName = $_FILES['image']['tmp_name'];
    $imageType = $_FILES['image']['type'];

    // Read the file
    $fp = fopen($tmpName, 'r');
    $data = fread($fp, filesize($tmpName));
    $data = addslashes($data);
    fclose($fp);


    $sql="INSERT INTO photos (photoName, caption, photoData, photoType, userName)
        VALUES
        ('$_POST[photoName]','$_POST[caption]','$tmpName','$imageType', '$currentUser')";

    //For debugging purposes
    if(!mysqli_query($con,$sql))
    {
        die('Error: ' . mysqli_error($con));
    }
    else
    {
        echo "Your Image has been Added";
    }   
}

then printing the image

if(isset($_POST['usersImage'])){
        //code to show images
        $user = $_POST['usersImage'];
        $sql = "SELECT * FROM `photos` WHERE userName = '$user'";
        $result = mysqli_query($con,$sql);
        while($row = mysqli_fetch_array($result)) 
        {
            switch ($row['photoType']) {
                case 'image/jpeg':

                echo "<tr>";  
                echo '<img src="data:image/jpeg;base64,'. base64_encode($row['photoData'])."\"></td>";   
                echo "</tr>"; 
                    //echo '<img src="image>' .$row['photoData']. '.jpeg'.'</p>';
                    //echo '<p id="caption">'.$row['caption'].' </p>';
                break;
            }           
        }
    }

as you can see my latest attempt was to use base64 encoding to print out the image my previous try was the commented out code

  • 写回答

2条回答 默认 最新

  • duansao20000508 2013-03-16 17:41
    关注

    When you display the image it has to be from its own request. src="" should contain a url to a script that will deliver the content with the correct MIME header image/jpeg.

    <?php
        $photo_bin = //binary data from query here;
    
        header("Content-Type: image/jpeg"); // or whatever the correct content type is.
        echo $photo_bin;
    

    Quick example^ of a php script that can be requested by the browser from an img tag.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站