怎样实现使用c++将图片存入mongodb数据库再取出来

来源:互联网 发布:java制表符 编辑:程序博客网 时间:2024/05/29 17:17

        网上有很多使用c#和java对mongdb进行读取的例子,但是很少有使用c++对其进行开发的例子,由于和c#和java的驱动不同,因此具体的实现方法也不一样,最多是大体的意思想通,而且我试了很久也没有找到直接将图片存入mongdb中的方法,只能是借助GridFS来进行存取,下面是我的代码。由于刚写代码,手法还不娴熟,没有加入错误判断,因此可读性较差,但是功能都已经实现了,供大家茶余饭后消遣了。

#include "stdafx.h"
#include<iostream>
#include<string>
#include<fstream>
#include<mongo\client\dbclient.h>
using namespace mongo;
using namespace bson;
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    //连接端口;
    DBClientConnection c;
    c.connect("localhost");
    
    //将图片转化到字符数组;
    char*ffile;
    string fileName =  "F:\\ceshi\\iphoto.jpg";  
    ifstream infile;  
    infile.open(fileName,ios::binary);  
    infile.seekg(0,ios::end);      
    int len = infile.tellg();     
    infile.seekg(0,ios::beg);
    ffile = new char[len+1];
    memset(ffile, '\0', len+1);  
    infile.read(ffile, len);  
    infile.close();  
    
    //新建GridFS;
    GridFS fs(c,"local");
    BSONObj fileobj = fs.storeFile(ffile,len,"photo");

    //将值插入数据库;
    BSONObjBuilder b;
    b.append("name", "peter");
    b.append("age", 33);
    b.append("photo",fileobj);
    BSONObj p = b.obj();
    c.insert("local.mydb",p);

    delete[]ffile;

    //读取图片数据;
    string filename ="F:\\ceshi\\output.jpg";
    ofstream out;
    out.open(filename,ios::binary);
    GridFS fsread(c,"local");
    fsread.findFile("photo").write(out);
    out.close();
    return 0;
}


1 0