您的位置:首页 > 数据库 > Mongodb

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

2014-08-15 10:30 681 查看
网上有很多使用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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐