Question

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?

Was it helpful?

Solution

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:

$record = array("name" => "my photo",
"photo" => new MongoBinData(file_get_contents("myself.jpg")));

$collection->insert($record);

This will then insert your image as binary into the DB. When retrieving it, just grab your record:

$record = $collection->findOne();
$imagebody = $record["photo"];

And echo them out onto a php file as per below

header('Content-Type: image/jpeg');
// Output the image
imagejpeg($imagebody);

OTHER TIPS

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/

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top