我是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());
}
?>
我得到的只是一张破碎的图像。请帮帮我..谢谢..
答案 0 :(得分:2)
只是检查一些事情
你应该使用&#34;新的MongoClient&#34; as&#34;新的Mongo&#34;已被诽谤。
尝试替换以下代码段:
$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