2012-05-17 48 views
0

我正在使用GridFS,並且我目前已經使用findOne來顯示單個圖像,但我希望它遍歷網格中的所有結果並將它們全部回顯到屏幕,這裏是我使用的代碼:迭代遍歷結果MongoDB和GridFS(PHP)

<?php 
try { 
    // open connection to MongoDB server 
    $conn = new Mongo; 

    // access database 
    $db = $conn->database; 

    // get GridFS files collection 
    $grid = $db->getGridFS(); 

    // retrieve file from collection 
    header('Content-type: image/png'); 
    $file = $grid->findOne(array('_id' => new MongoId('4fb437dbee3c471b1f000001'))); 

    // send headers and file data 

    echo $file->getBytes(); 
    exit; 

    // disconnect from server 
    $conn->close(); 
} catch (MongoConnectionException $e) { 
    die('Error connecting to MongoDB server'); 
} catch (MongoException $e) { 
    die('Error: ' . $e->getMessage()); 
} 
?> 

感謝

回答

0

使用「發現」與「findOne」,這將返回一個結果集,你可以通過在foreach,像循環:

$ files = $ grid-> find({});

foreach($ files as $ file){echo $ file-> someData; }

+0

我試過這個$ files = $ grid-> find(); foreach($ files as $ file){echo $ file-> getBytes(); }雖然它不起作用 –

+0

如果你想要所有的文件,試試find({})(注意大括號爲空參數)。而不是顯示$ file-> getBytes();在你的循環中,嘗試「print_r($ file);」只是爲了調試,看看你是否有任何東西。 – jbnunn

0

一般情況下,如果你在網頁上顯示圖像,你想有一堆像<img src="someUrl" />標籤,然後讓每個someUrl手柄得到一個單一的形象。

0

您將標頭設置爲image/png,以便瀏覽器只需要一個圖像。

您可以做的是將其更改爲text/html文檔,並使用數據URI方案嵌入圖像(請參閱http://en.wikipedia.org/wiki/Data_URI_scheme),然後將圖像輸出到一系列圖像標記中。

<!doctype html> 
<html> 
    <head> 
     <meta charset="UTF-8"> 
     <title>My images</title> 
    <head> 
    <body> 
    <?php 
    /* ... db connection/init code ... */ 

    $files = $grid->find({}); 

    foreach($files as $file) { 
     $encodedData = base64_encode($file->getBytes()); 
     echo "<img src=\"data:image/png;base64,{$encodedData}\">"; 
     echo "<br>"; 
    } 
    ?> 
    </body> 
</html> 

注意,你可能想如果圖像的MIME類型,並相應改變,並設置ALT,width和height屬性使用文件的元數據來檢測。

希望這會有所幫助。