使用php的MongoDB中未显示图像


Image not displaying in MongoDB using php

我是MongoDB和php的新手,我的问题是存储在我的位置数据库中的图像没有显示。我有一个测试代码,可以插入我的所有数据,包括我的图像名称。该图像名称将用于访问存储在同一数据库中的图像。

这是我的插入数据代码

 <?php
try {
    // open connection to MongoDB server
    $conn = new Mongo('localhost');
    //access database
    $db = $conn->location;
    //access collection
    $collection = $db->loc;
    // insert a new document
    $filename = "102120140913290.jpg";
    $data = array(
        'name' => 'Butuan',
        'latitude'=> 8.9576751,
        'longitude' => 125.5963283,
        'imagename' => $filename
        );
    $collection->insert($data);
    echo 'Inserted document withy ID:' . $data['_id'] . '<br/>';
    $img = $db->getGridFS();
    $path = "C:''xampp''htdocs''mysite''upload''";

    $storedfile =   $img->storeFile($path . $filename,
             array("metadata" => array("filename" => $filename),
             "filename" => $filename));
    echo 'Stored file ID:' . $storedfile;
} catch (MongoConnectionException $e) {
  die('Error connecting to MongoDB server');
} catch (MongoException $e) {
  die('Error: ' . $e->getMessage());
}
?>

这是我的获取图像代码

<?php
    try{
        $conn = new Mongo('localhost');
        $db = $conn->location;
        $collection = $db->loc;
        $cursor = $collection->find();
        $imgname;
        echo $cursor->count(). 'document(s) found. <br/>';
        foreach($cursor as $obj){
            $imgname = $obj['imagename'];
        }

        $gridFS = $db->getGridFS();
        $image = $gridFS->findOne($imgname);
        header('Content-type: image/jpeg');
        echo $image->getBytes();
    } catch (MongoConnectionException $e) {
      die('Error connecting to MongoDB server');
    } catch (MongoException $e) {
      die('Error: ' . $e->getMessage());
    }
    ?>

我得到的只是一个破碎的图像。请帮忙。。非常感谢。

只检查

您应该使用"新MongoClient",因为"新Mongo"已经被降级了。

尝试替换以下代码段:

$gridFS = $db->getGridFS();
$image = $gridFS->findOne($imgname);
$imageFile = $image->getBytes();
header('Content-type: image/jpeg');
header("Content-Length: " . strlen($imageFile));
ob_clean();
echo $imageFile;

另请查看storeUpload功能http://php.net/manual/en/mongogridfs.storeupload.php