【问题标题】:Send image in http post via json object using cpprest使用 cpprest 通过 json 对象在 http post 中发送图像
【发布时间】:2015-10-28 14:02:41
【问题描述】:

我正在使用库 cpprest。我正在尝试将图像文件作为二进制文件发送到端点。我需要它遵循

的json结构
{
    "image": "binaryfile",
    "type": "file"
}

但是我不知道该怎么做,只有接收二进制数据的好例子。这就是我目前所拥有的:

ifstream imageToConvert;

imageToConvert.open("path to file", ios::binary);

ostringstream ostrm;


if (imageToConvert.is_open())
{
    ostrm << imageToConvert.rdbuf();
    imageToConvert.close();
}
imageToConvert.close();

//build json string to convert
string MY_JSON = ("{\"image\" : \"");
MY_JSON += (ostrm.str());
MY_JSON += ("\",\"type\" : \"file\"}");

//set up json object
json::value obj;
obj.parse(utility::conversions::to_string_t(MY_JSON));

但是这会引发内存错误异常。所以我的问题是,从文件中获取此二进制数据的最佳方法是什么,以及如何正确构建我的 json 对象以在我的帖子中发送?

【问题讨论】:

  • 你看过this吗?它对你有帮助,所以我不确定这是否会破坏交易。
  • 我不确定这在这种情况下是否对我有帮助。在这一点上,我真的没有要构建的 json。我需要使用图像文件的二进制输出并将其添加到 json 对象中,如果有意义的话,cpprest 库将允许我发送。

标签: c++ json


【解决方案1】:

转换为ostringstream 以及随后将字符串连接到 MY_JSON 会产生错误,因为您的二进制图像数据很可能包含一些不可打印的字符。

我认为您应该将二进制数据从ifstream 编码为base64 字符串并将该编码字符串传递给MY_JSON。在服务器端使用 base64-decoding 解码image 字段中的数据。

可在此处找到 C++ 的基本 Base64 编码/解码: http://www.adp-gmbh.ch/cpp/common/base64.html

还有关于如何在JS中解码Base64的问题:How to send image as base64 string in JSON using HTTP POST?

附:说到示例代码,你可以先把你的数据加载到std::vector

std::ifstream InFile( FileName, std::ifstream::binary );
std::vector<char> data( ( std::istreambuf_iterator<char>( InFile ) ), std::istreambuf_iterator<char>() );

然后你调用

std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len);

像这样:

std::string Code = base64_encode((unsigned char*)&data[0], (unsigned int)data.size());

最后,将Code 添加到 JSON:

MY_JSON += Code;   // instead of ostrm.str

【讨论】:

  • 完美运行。我能够使用 base64 字符串并使用预期的函数构建 json 对象,而不是传入字符串。感谢 base64 编码代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-15
  • 1970-01-01
  • 2011-10-02
  • 2012-11-14
  • 1970-01-01
相关资源
最近更新 更多