2013-03-16 34 views
0

有在我的MySQL數據庫的顯示圖像的大時間問題店面形象到MySQL數據庫和PHP和顯示

我將其存儲在一個LONGBLOB類型

顯示圖像時,我收到了破碎圖像圖標

這裏是代碼,用於存儲圖像

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"; 
    } 
} 

然後打印圖像

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; 
      }   
     } 
    } 

,你可以看到我的最新嘗試是使用base64編碼打印出來的圖像 我以前嘗試被註釋掉的代碼

回答

3

當你顯示它必須從自己的請求圖像。 src=""應該包含一個腳本的URL,該腳本將使用正確的MIME頭文件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; 

簡單的例子,可以通過瀏覽器從img標籤請求一個PHP腳本的^。

+0

我試過這個解決方案,仍然給我一個破碎的圖像圖標 – user1050632 2013-03-16 17:51:15

+0

以及試着去你的瀏覽器中的網址。如果這不起作用,那麼你做錯了什麼,你肯定會得到一個破碎的IMG圖標。 – 2013-03-16 17:52:24

+0

像M.K Price的答案,你必須使用'addslashes'來將二進制數據插入到數據庫中。 – 2013-03-16 17:53:55

1

確認很重要。你正在爲自己打開如此多的安全問題。

在sql語句中不要使用$ _POST/$ _GET。逃脫它們,更好的是,使用PDO語句。驗證圖像實際上是圖像,此時,您可以將任何類型的文件輸入到表格中。

正如您所發現的,將圖像存儲在數據庫中比在文件系統上存儲要困難得多。通常情況下,在文件系統上存儲圖像比在表格中存儲更多的參數。

快速查看插入代碼後,我不太確定爲什麼要向二進制數據添加斜槓。刪除對addslahes的調用,並嘗試。