【薦】PHP操作MongoDB GridFS 隱藏檔,如圖片檔案

來源:互聯網
上載者:User

標籤:

GridFS是MongoDB的一個內建功能,它提供一組檔案操作的API以利用MongoDB隱藏檔,GridFS的基本原理是將檔案儲存在兩個Collection中,一個儲存檔案索引,一個儲存檔案內容,檔案內容按一定大小分成若干塊,每一塊存在一個Document中,這種方法不僅提供了檔案儲存體,還提供了對檔案相關的一些附加屬性(比如MD5值,檔案名稱等等)的儲存。

<?php // 初始化gridfs $conn = new Mongo(); // 串連MongoDB $db = $conn->photos; // 選擇資料庫 $collection = $db->getGridFS(); // 取得gridfs對象 // gridfs有三種方式隱藏檔 // 第一種直接隱藏檔 $id = $collection->storeFile("./logo.png"); // 第二種隱藏檔二進位流 $data = get_file_contents("./logo.png"); $id = $collection->storeBytes($data,array("param" => ‘附加參數將隨圖片一起存入‘)); // 第三種儲存直接表單提交的檔案$_FILES $id = $collection->storeUpload(‘upfile‘); // 相當於 $id = $collection->storeFile($_FILES[‘upfile‘][‘tmp_name‘]); //--------------以上是儲存圖片--下面開始讀取圖片---------------- // 儲存成功後返回$id = md5字串 $logo = $collection->findOne(array(‘_id‘=>$id)); // 以_id為索引取得檔案 header(‘Content-type: image/png‘); // 輸出圖標題 echo $logo ->getBytes(); // 輸出資料流 ?>

特別備忘:

通過 $id = $collection->storeFile($_FILES[‘upfile‘][‘tmp_name‘]); 產生的ID,是MongoDB的 ID對象,而不是一個 字串!如以下格式:

{   "_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" }

不過,我們可以通過 $id = strval($id),把上述 ID對象 字串化,如可得到上述的 525418525ba8a18c1b000001 值,再把這個值存到MySQL資料庫中,到時候可通過這個 字串ID 作為條件,找到相應的MongoDB資源。參考代碼如下:

$conn = new Mongo(C(‘127.0.0.1:27017‘)); //如果設定了密碼自己配置DSN$db=$conn->selectDB(‘edu_sns‘);  // 選擇資料庫$collection = $db->getGridFS(‘zk_attach‘); // 選擇集合,相等於選擇資料表$id=$_GET[‘id‘];$object=$collection->findOne(array(‘_id‘=>new MongoId($id)));header(‘Content-type: image/png‘);echo $object->getBytes();

 

 

 

 

最近因工作需要研究了下GridFS,並整理了個Demo出來。。分享一下經驗。。

gfs.php檔案

<?php// 串連Mongo並初始化GFS$conn = new Mongo(C(‘127.0.0.1:27017‘)); //如果設定了密碼自己配置DSN$db=$conn->selectDB(‘edu_sns‘);  // 選擇資料庫$collection = $db->getGridFS(‘zk_attach‘); // 選擇集合,相等於選擇資料表// 上傳圖片if (isset($_FILES[‘upfile‘])) {// 儲存新上傳的檔案$size = $_FILES[‘upfile‘][‘size‘];$md5 = md5_file($_FILES[‘upfile‘][‘tmp_name‘]);$exists = $collection->findOne(array(‘md5‘ => $md5,‘length‘ => $size), array(‘md5‘));if (empty($exists)) {$collection->storeUpload(‘upfile‘);// 或修改為如下代碼,並存入一些自訂參數/*$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>圖片路徑為: <font color=red>http://{$_SERVER[‘HTTP_HOST‘]}{$_SERVER[‘REQUEST_URI‘]}?img={$md5}</font></p>";} elseif ($id = $_GET[‘img‘]) { // 產生圖片// 索引圖片檔案$image = $collection->findOne(array(‘md5‘ => $id));// 設定文件類型,顯示圖片$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‘]) { // 刪除圖片$s = $collection->remove(array(‘md5‘ => $id));header(‘Location:‘ . $_SERVER[‘HTTP_REFERER‘]);} else { // 圖片列表$cursor = $collection->find();foreach ($cursor as $obj) :echo ‘<p><a href="?img=‘ . $obj->file[‘md5‘] . ‘&w=800"><img src="?img=‘ . $obj->file[‘md5‘] . ‘" border="0" /></a><a href="?del=‘ . $obj->file[‘md5‘] . ‘">刪除</a></p>‘;endforeach;}?>

 

thumb.php 縮圖檔案

<?phpclass Thumb {/** * 以最大寬度縮放映像 * * @param string $im 映像中繼資料 * @param float $w 最大寬度 */static function maxWidth($im, $w) {if (empty($im) || empty($w) || !is_numeric($w)) {throw new Exception("缺少必須的參數");}$im = imagecreatefromstring($im); // 建立映像list ($im_w, $im_h) = self::getsize($im); // 擷取映像寬高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);}/** * 以最大高度縮放映像 * * @param string $im 映像中繼資料 * @param float $w 最大高度 */static function maxHeight($im, $h) {if (empty($im) || empty($h) || !is_numeric($h)) {throw new Exception("缺少必須的參數");}$im = imagecreatefromstring($im); // 建立映像list ($im_w, $im_h) = self::getsize($im); // 擷取映像寬高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);}/** * 產生固定大小的映像並按比例縮放 * * @param string $im 映像中繼資料 * @param float $w 最大寬度 * @param float $h 最大高度 */static function fixed($im, $w, $h) {if (empty($im) || empty($w) || empty($h) || !is_numeric($w) || !is_numeric($h)) {throw new Exception("缺少必須的參數");}$im = imagecreatefromstring($im); // 建立映像list ($im_w, $im_h) = self::getsize($im); // 擷取映像寬高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);}//echo "$im_w x $im_h <br/> $new_w x $new_h <br/> $x $y";exit;// 開始建立縮放後的映像$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);}/* * 擷取映像大小 *  * @param string $im 映像中繼資料 * @return array */protected static function getsize($im) {return array(imagesx($im),imagesy($im));}}?>

 

index.html HTML表單檔案

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>Mongo Gridfs</title></head><body><form action="gfs.php" method="post" enctype="multipart/form-data">    <input type="file" name="upfile"  />    <input type="submit" value="upload" /> <a href="gfs.php">查看圖片</a></form></body></html>

 

 

 

延伸閱讀:

Windows下安裝MongoDB

【薦】PHP操作MongoDB GridFS 隱藏檔,片檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.