我正在尝试从mongoDB中检索图像并在Web浏览器中显示它。但它没有用。这是我用于插入和检索的代码
要上传的代码:
<?php
//If you wanted to store the uploaded image in MongoDB, you could do the following in the script handling the form submission:
if(isset($_REQUEST['formsubmit']))
{
$m = new MongoClient();
$coll = $m->test;
$gridFS = $coll->getGridFS();
$tag = $_REQUEST['username'];
$gridFS->storeUpload('pic',array("tag"=>$tag));
echo 'File Uploaded Successfully';
$m->close();
}
?>
<!-- image and any file uploaded in mongodb -->
<html>
<head> Upload Image</head>
<body>
<!--The name of the uploaded file to store. This should correspond to the file field's name attribute in the HTML form. -->
<form method="POST" enctype="multipart/form-data">
<label for="username">Username:</label>
<input type="text" name="username" id="username" />
<label for="pic">Please upload a profile picture:</label>
<input type="file" name="pic" id="pic" />
<input type="submit" value="Register" name="formsubmit"/>
</form>
</body>
</html>
检索图像并在浏览器中显示的代码:
<?php
//If you wanted to store the uploaded image in MongoDB, you could do the following in the script handling the form submission:
$m = new MongoClient();
$coll = $m->test;
$gridFS = $coll->getGridFS();
?>
<html>
<head>Displaying Image</head>
<body>
<?php
header('content-type: image/jpg');
echo '<img src=' . $gridFS->findOne(array("tag"=>"temp123"))->getBytes() .'>'. '</img>';
?>
</body>
</html>
有人可以帮帮我吗? 谢谢
答案 0 :(得分:0)
非常感谢这个帮助你的绝佳机会。 首先..GridFS用于保存超过16mb大小的文件。你没有提到这个问题。 以下代码用于保存小于16mb的图像。
***************** Image insertion**************
$target_dir = "upload/";
$target_file = $target_dir . basename($_FILES["pic"]["name"]); //Image:<input type="file" id="pic" name="pic">
$tag = $_REQUEST['username'];
$m = new MongoClient();
$db = $m->test; //mongo db name
$collection = $db->storeUpload; //collection name
//-----------converting into mongobinary data----------------
$document = array( "user_name" => $tag,"image"=>new MongoBinData(file_get_contents($target_file)));
//-----------------------------------------------------------
if($collection->save($document)) // saving into collection
{
echo "One record successfully inserted";
}
else
{
echo "Insertion failed";
}
******************Image Retrieving******************
public function show()
{
$m=new MongoClient();
$db=$m->test;
$collection=$db->storeUpload;
$record = $collection->find();
foreach ($record as $data)
{
$imagebody = $data["image"]->bin;
$base64 = base64_encode($imagebody);
?>
<img src="data:png;base64,<?php echo $base64 ?>"/>
<?php
}
}
}
?>
希望你能尝试一下。享受编码。祝福。