2017-03-05 82 views
0

我是我的数据库中的图像数据作为mediumblob并试图检索它作为图像时,用户通过它的相应的ID选择图片。在任何人跳过我的喉咙之前,是的,我意识到这是一个更顺畅的过程,存储在文件服务器上,并以这种方式检索,但这是一个班级,这是教授想要的。获取“图像无法显示,因为它包含错误”

<HTML> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>BLOB Data Type Tutorial</title> 
</head> 

<body> 
<form action="images.php" method="POST" enctype="multipart/form-data"> 
    Select Picture: <input type="pictureID" name="pictureID"> <input type="submit" value="submit" name="submit"> 

</form> 
<?php 

    $link = mysqli_connect('127.0.0.1:3306','user',''); 
    $link; 
    mysqli_select_db($link, "media"); 

    $sql = "SELECT * FROM images"; 
    $result = mysqli_query($link,$sql); 
    echo "<table>"; 
    echo "<tr><th>Picture</th><th>Size KB</th><th>Title</th></tr>"; 

    if($result === FALSE){ 
     echo "failed"; 
     die(mysql_error()); 
    } 

    while($row = mysqli_fetch_array($result)) { 
     $Picture = $row['Picture']; 
     $Size = $row['Size KB']; 
     $Title = $row['Title']; 
     echo "<tr><td style ='width: 50px;'>".$Picture."</td><td style='width: 60px;'>".$Size."</td><td>".$Title."</td></tr>"; 
    } 

    echo "</table>"; 

    if(isset($_POST['pictureID'])) 
    { 
    $imgId = $_POST['pictureID']; 
    echo $imgId; 
    if (!empty($imgId)) { 
    $sqliCommand = "SELECT Picture FROM images WHERE Picture = $imgId"; 
    $result = mysqli_query($link, $sqliCommand); 
    $row = mysqli_fetch_assoc($result); 
    header("Content-type: image/jpeg"); 
    echo $row['Image']; 
    } 
    } 
    else 
    { 
     echo "^ Please select a picture! ^"; 
    } 
?> 


<br> 
<h4> 
    <a href="./index.html">Main Menu</a> <br> 
</h4> 
</body> 
</HTML> 

任何提示/帮助表示赞赏!

+0

找一位新教授。他真的不知道他在教什么,如果那是他想要你学习的东西。有许多事情是错误的,不仅仅是图像数据在数据库中的存储,还有缺乏准备好的语句(用户输入),表格中的输出(尽管如果存在大量具有相应数据的图像,这可能是有保证的这应该是可比的/可排序的)。 – junkfoodjunkie

回答

0

这是因为页面顶部也有html代码导致的。当执行header("Content-type: image/jpeg");时,chrome会将整个页面的内容解释为包含html的图像数据。

要解决这个问题,当id在脚本顶部传递代码时输出图像输出,并在输出图像时立即退出脚本,否则它下面的代码也会输出。

它应该做的事是这样的:

<?php 
    //this should be at top of php file, above html code 
    link = mysqli_connect('127.0.0.1:3306','user','');  
    mysqli_select_db($link, "media"); 
    if(isset($_POST['pictureID'])) 
    { 
     $imgId = $_POST['pictureID']; 
     //echo $imgId; nothing else expect image should be echoed 
     if (!empty($imgId)) { 
      $sqliCommand = "SELECT Image FROM images WHERE Picture = $imgId";// select Image here so not select picture as you did earlier 
      $result = mysqli_query($link, $sqliCommand); 
      $row = mysqli_fetch_assoc($result); 
      mysqli_close($link);//close mysqli as script gonna exit after echoing image. 
      header("Content-type: image/jpeg"); 
      echo $row['Image']; 
      exit();// this is important 
     } 
    } 
?> 
<html> 
    <body> 
    <!-- rest of the code --> 

阅读我在写代码的注释。

如果您将标头设置为图像类型,则页面上一定不会出现图像二进制代码。

如果问题仍然存在,那么注释标题行(这将使页面以文本形式显示),并查看页面中是否有其他内容以二进制形式呈现图像数据。

+0

谢谢你,先生,可能Hera对待你好! – blackmail242

相关问题