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

        网上有很多使用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;
}


  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值