源地址
#include <algorithm>
#include <iostream>
#include <ostream>
#include <bsoncxx/json.hpp>
#include <bsoncxx/stdx/make_unique.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/gridfs/bucket.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>
#include <bsoncxx/types/bson_value/view.hpp>
#include <fstream>
#include <bsoncxx/array/view.hpp>
#include <bsoncxx/builder/basic/array.hpp>
#include <bsoncxx/builder/basic/document.hpp>
#include <bsoncxx/builder/basic/kvp.hpp>
#include <bsoncxx/document/value.hpp>
#include <bsoncxx/document/view.hpp>
#include <bsoncxx/json.hpp>
#include <bsoncxx/stdx/string_view.hpp>
#include <bsoncxx/string/to_string.hpp>
#include <bsoncxx/types.hpp>
#include <bsoncxx/types/bson_value/view.hpp>
#include <bsoncxx/builder/stream/array.hpp>
#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/builder/stream/helpers.hpp>
#include <bsoncxx/builder/basic/document.hpp>
using namespace mongocxx;
using namespace bsoncxx;
using bsoncxx::stdx::make_unique;
using namespace bsoncxx;
using namespace builder::stream;
int main() {
std::cout << "start" << std::endl;
mongocxx::instance inst{
};
mongocxx::client conn{
mongocxx::uri{
}};
auto db = conn["test"];
auto bucket = db.gridfs_bucket();
mongocxx::gridfs::uploader up = bucket.open_upload_stream("img");
std::ifstream fp;
fp.open("D:/2.png", std::ios::binary | std::ios::in);
fp.seekg(0, fp.end);
size_t allLength = fp.tellg();
fp.seekg(0, fp.beg);
char* buff = new char[allLength + 10]{
0 };
fp.read(buff, allLength);
up.write(reinterpret_cast<uint8_t*>(const_cast<char*>(buff)), allLength);
delete[]buff;
buff = nullptr;
auto result = up.close();
auto kk = result.id();
std::string idStr = "620f1faaf06f0000de000e52";
bsoncxx::stdx::string_view fileIdSv = idStr;
auto bsonId = oid(fileIdSv);
builder::stream::document build_doc;
build_doc << "id" << bsonId;
auto doc = build_doc.view();
auto downloader = bucket.open_download_stream(doc["id"].get_value());
auto file_length = downloader.file_length();
auto bytes_counter = 0;
auto buffer_size = std::min(file_length, static_cast<std::int64_t>(downloader.chunk_size()));
auto buffer = make_unique<std::uint8_t[]>(static_cast<std::size_t>(buffer_size));
std::fstream fq;
fq.open("E:/Desktop/3.png", std::ios::binary | std::ios::out);
while (auto length_read =
downloader.read(buffer.get(), static_cast<std::size_t>(buffer_size))) {
bytes_counter += static_cast<std::int32_t>(length_read);
fq.write(reinterpret_cast<char*>(const_cast<uint8_t*>(buffer.get())), length_read);
}
fq.close();
std::cout << "总共接收字节数" << bytes_counter << std::endl;
return 0;
}