how can we upload & retrieve files into mongodb using PHP,by directly using a form...like uploading profile picture during registration. Please Can anyone send me the code?
uploading and retrieving files into mongodb with php
3.8k Views Asked by Vamsi Krish At
3
There are 3 best solutions below
0

I would suggest you to go for GridFS , which is meant for saving the files . Here is a good example : http://learnmongo.com/posts/getting-started-with-mongodb-gridfs/ , more about GridFS here : http://docs.mongodb.org/manual/core/gridfs/
0

Really thankful for this wonderful opportunity to help you. First of all..GridFS is using for saving files that more than 16mb size.The following code will help you to upload and retrieve image less than 16 mb.
***************** 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
}
}
}
?>
Hope you will try this.Enjoy coding.Stay Blessed.
I don't have the code sample handy just now, but it's very straightforward really. Upload the file to a temp location as you would normally do via a file submitting, then grab the file content and create a
MongoBinData
object as below:This will then insert your image as binary into the DB. When retrieving it, just grab your record:
And
echo
them out onto a php file as per below