zoukankan      html  css  js  c++  java
  • 公益图书馆-MongoDB-笔记

    1、http://cn2.php.net/manual/en/class.mongogridfs.php

    class FileController extends SyController{
    
        /**@author yj
         * @description 要使用下面两个函数,必须先初始化
         * Date: 14-9-3
         */
        public function init(){
            header("Content-type:text/html;charset=utf-8");
            // 连接Mongo并初始化GFS
            // 数据库命名file
            $conn = new MongoClient();
            $db = $conn->picDB;
            // 取得gridfs对象
            $prefix = 'pic';
            $collection = $db->getGridfs($prefix);
            return $collection;
        }
    
        /**@author yj
         * @description 将所有二进制文件上传入MongoDB,并返回文件索引ID值
         * 专用于表单提交资源方式
         * Date: 14-9-2
         * Time: 11:21
         */
        public function upload($filename,$collection)
        {
            $id = $collection->storeUpload($filename);
    //        获取上一步的id对象中的_id字符串
            $id = strval($id);
            return $id;
    
        }
        /**@author yj
         * @description 根据ID值删除对应资源
         * Date: 14-9-3
         */
        public function delete($id,$collection)
        {
    //        将id字符串转化成id对象
            $collection->delete(new MongoId($id));
        }
        /**
         * @author:yj
         * 利用资源id和资源type把资源从mongoDB中获取并显示
         */
        public function get()
        {
            header("Content-type:text/html;charset=utf-8");
            $conn = new MongoClient();
            $db = $conn->picDB;
    //      取得gridfs对象
            $prefix = 'pic';
            $collection = $db->getGridFS($prefix);
    
            //获取id和type
            $id = I('get.id');
            $type = I('get.type');
            //返回数据
            $object = $collection->findOne(array('_id' => new MongoId($id)));
            header('Content-type:'.$type);
            echo $object->getBytes();
        }

    注意,存储在mongoDB里面的'_id'是一个对象ID,也叫Object ID。而我们存入mysql里面的ID是一个字符串ID。转换方法如下:

    $id = strval($id);  //对象ID中获取字符串ID
    '_id' => new MongoId($id)  //将字符串ID转化成Mongo对象ID

    2、在其他控制器里若想要使用MongoDB

    //初始化MongoDB数据库
    $collection = R('file/init');
    //使用表单上传文件,$key是表单中input标签的name
    $id = R('file/upload',array($key,$collection));
    //根据字符串ID $avatar_id来删除Mongo里面的对应.files .chunks文件
    $collection->delete(new MongoId($avatar_id));
    //根据字符串ID直接从Mongo里面获取资源并根据type显示出来
    <img src="/file/get/type/image/id/{$avatar_id}"/>
  • 相关阅读:
    hdu_5750_Dertouzos(线性筛)
    hdu_5748_Bellovin(LIS)
    Codeforces Round #364 (Div. 2) C.They Are Everywhere
    Codeforces Round #364 (Div. 2) D. As Fast As Possible
    [BZOJ 2456]Mode(神奇的抵销)
    [poj3046]Ant Counting(母函数)
    [poj1742]coin
    [poj3666]Making the Grade(DP/左偏树)
    【POJ各种模板汇总】(写在逆风省选前)(不断更新中)
    [USACO2004][poj1989]The Cow Lineup(乱搞)
  • 原文地址:https://www.cnblogs.com/wingjay/p/3954448.html
Copyright © 2011-2022 走看看