Gridfs is a built-in feature of MongoDB that provides a set of file manipulation APIs to utilize MongoDB to store files, the basic principle of Gridfs is to save files in two collection, a save file index, a save file content, The contents of the file are divided into blocks of a certain size, and each piece exists in a document, which not only provides the file storage, but also provides the storage of some additional properties related to the file (such as MD5 value, file name, etc.).
<?php//Initialize Gridfs $conn = new Mongo (); Connect MongoDB $db = $conn->photos; Select Database $collection = $db->getgridfs (); Get Gridfs object//Gridfs There are three ways to store files//The First Direct storage file $id = $collection->storefile ("./logo.png"); The second binary stream of storage files $data = Get_file_contents ("./logo.png"); $id = $collection->storebytes ($data, Array ("param" + + ' additional parameters will be saved with the image)); The third file to save the direct form submission $_files $id = $collection->storeupload (' upfile '); Equivalent to $id = $collection->storefile ($_files[' upfile ' [' tmp_name ']); --------------above is to save the picture--the following begins to read the picture----------------//Save after successful return $id = MD5 string $logo = $collection->findone (' _id ' = > $id)); Get the file header (' Content-type:image/png ') with _id as index; Output image head echo $logo->getbytes (); Output data stream?>
Special remark:
by $id = $collection->storefile ($_files[' upfile ' [' tmp_name ']) , the resulting ID is the ID object of MongoDB, not a String ! As in the following format:
{ "_id": ObjectId ("525418525ba8a18c1b000001"), "filename": "D:\\php\\xampp\\tmp\\php8116.tmp", " Uploaddate ": Isodate (" 2013-10-08t14:36:02.0z "), " Length ": Numberint (55862), " ChunkSize ": Numberint (262144 ), "MD5": "A6f19f3434f0b36bb2611cd4c6d82b35"}
However, we can string the above ID object by $id = Strval ($id), if we can get the above 525418525ba8a18c1b000001 Value, and then the value is stored in the MySQL database, the string ID can be used as a condition to find the corresponding MongoDB resources. The reference code is as follows:
$conn = new Mongo (C (' 127.0.0.1:27017 ')); If you set the password yourself configure dsn$db= $conn->selectdb (' Edu_sns '); Select Database $collection = $db->getgridfs (' Zk_attach '); Select the collection, equal to the Select data table $id=$_get[' ID '), $object = $collection->findone (Array (' _id ' =>new MongoId ($id))), header (' Content-type:image/png '); Echo $object->getbytes ();
Recently, due to work needs to study the next Gridfs, and compiled a demo out. Share your experience.
gfs.php file
<?php//Connect Mongo and Initialize Gfs$conn = new Mongo (C (' 127.0.0.1:27017 ')); If you set the password yourself configure dsn$db= $conn->selectdb (' Edu_sns '); Select Database $collection = $db->getgridfs (' Zk_attach '); Select Collection, equal to select data table//Upload picture if (isset ($_files[' upfile ')) {//Save newly uploaded file $size = $_files[' upfile '] [' size ']; $MD 5 = Md5_file ($_ files[' upfile ' [' tmp_name ']); $exists = $collection->findone (Array (' MD5 ' = $MD 5, ' length ' = = $size), Array (' MD5 '), if (Empty ($exists)) {$collection->storeupload (' upfile ');//or modify to the following code and deposit some custom parameters/* $filename =$_files[' Upfile ' [' name ']; $filetype =$_files[' upfile ' [' type ']; $tmpfilepath =$_files[' upfile '] [' tmp_name ']; $id = $gridfs- >storefile ($tmpfilepath, Array (' filename ' = = $filename, ' filetype ' = + $filetype)); */} else {unlink ($_files[' Upfile ' [' tmp_name ']);} echo "<p> picture path: <font color=red>http://{$_server[' http_host ']}{$_server[' Request_uri ']}?img={$md 5} </font></p> ";} ElseIf ($id = $_get[' img ')} {//Generate picture/index picture file $image = $collection->findone (Array (' MD5 ' = $id));//Set document type, display picture $img_bytes = $image->getbytes (); Include_once ' thumb.php '; $w = Is_numeric ($_get[' W '))? Intval ($_get[' W ']): 100; Thumb::maxwidth ($img _bytes, $w);} ElseIf ($id = $_get[' del ') {//delete picture $s = $collection->remove (Array (' MD5 ' = $id)); header (' Location: '. $_server[' HT Tp_referer ']);} else {//Picture list $cursor = $collection->find (); foreach ($cursor as $obj): Echo ' <p><a href= '? img= '. $obj->fil e[' MD5 '. ' &w=800 ' >file[' MD5 '). ' "border=" 0 "/></a><a href="? del= '. $obj->file[' MD5 '). ' > Delete </a></p> '; endforeach;}? >
thumb.php thumbnail files
<?phpclass Thumb {/** * scales image at maximum width * * @param string $im image metadata * @param float $w Maximum width */static function maxWidth ($im, $w {if (empty ($im) | | empty ($w) | |!is_numeric ($W)) {throw new Exception ("Missing required argument");} $im = imagecreatefromstring ($im); Create image list ($im _w, $im _h) = Self::getsize ($im); Gets the image width height if ($im _w > $w) {$new _w = $w; $new _h = $w/$im _w * $im _h;} else {$new _w = $im _w; $new _h = $im _h;} $DST _im = Imagecreatetruecolor ($new _w, $new _h); imagecopyresampled ($dst _im, $im, 0, 0, 0, 0, $new _w, $new _h, $im _w, $im _h); Header (' Content-type:image/jpeg '); Imagepng ($dst _im); Imagedestroy ($dst _im); Imagedestroy ($im);} /** * Scales the image at maximum height * * @param string $im image metadata * @param float $w Maximum height */static function maxheight ($im, $h) {if ($im) | | Empty ($h) | | !is_numeric ($h)) {throw new Exception ("Missing required argument");} $im = imagecreatefromstring ($im); Create image list ($im _w, $im _h) = Self::getsize ($im); Gets the image height if ($im _h > $h) {$new _w = $h/$im _h * $im _w; $new _h = $h;} else {$new _w = $im _w; $new _h = $im _h;} $DST _im = iMagecreatetruecolor ($new _w, $new _h); imagecopyresampled ($dst _im, $im, 0, 0, 0, 0, $new _w, $new _h, $im _w, $im _h); Header (' Content-type:image/jpeg '); Imagepng ($dst _im); Imagedestroy ($dst _im); Imagedestroy ($im);} /** * Generates fixed-size images and scales * @param string $im image metadata * @param float $w Maximum width * @param float $h Maximum height */static function fixed ($i M, $w, $h) {if (empty ($im) | | empty ($w) | | empty ($h) | |!is_numeric ($w) | |!is_numeric ($H)) {throw new Exception ("Missing required arguments" );} $im = imagecreatefromstring ($im); Create image list ($im _w, $im _h) = Self::getsize ($im); Get Image Height if ($im _w > $im _h | | $w < $h) {$new _h = intval (($w/$im _w) * $im _h); $new _w = $w;} else {$new _h = $h; $new _w = Intval (($h/$im _h) * $im _w);} _w, $new _h); imagecopyresampled ($dst _im, $im, 0, 0, 0, 0, $new _w, $new _h, $im _w, $im _h); header (' Content-type:image/jpeg ') ; Imagepng ($dst _im); Imagedestroy ($dst _im); Imagedestroy ($im);} /* * Get imagesSize * * @param string $im image metadata * @return array */protected static function GetSize ($im) {return Array (Imagesx ($im), images Y ($im));}}? >
index.html HTML form Files
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
Extended reading:
Installing MongoDB under Windows
"Recommended" PHP operation MongoDB gridfs storage files, tablet files