在web浏览器中显示从mongodb检索到的图像


Displaying images retrieved from mongodb in web browser?

我正试图从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>
有谁能帮我吗?谢谢你

非常感谢有这个机会来帮助你。首先,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
}
}
}
?>

希望你能尝试一下。喜欢编程。保持祝福。