2

I am using the library cpprest. I am trying to send an image file as a binary file to an endpoint. I need it to follow the json structure of

{
    "image": "binaryfile",
    "type": "file"
}

However I don't know how to do that and only fine examples on receiving binary data. So this is what I have so far:

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));

however this throws a memory fault exception. So my questions are, what is the best way to get this binary data from the file, and how do I correctly build my json object to send off in my post?

ollydbg23
  • 1,124
  • 1
  • 12
  • 38
yaegerbomb
  • 1,154
  • 4
  • 22
  • 37
  • Have you looked at [this](http://stackoverflow.com/questions/15206705/reading-json-file-with-boost)? It does you boost so I'm not sure if that's a deal breaker or not. – NathanOliver Apr 16 '15 at 15:03
  • I'm not sure this helps me in this situation. I dont really have the json to build at this point. I need to use the binary output of an image file and add it to a json object that the cpprest library will allow me to send off if that makes sense. – yaegerbomb Apr 16 '15 at 15:10

1 Answers1

3

The conversion to ostringstream and later concatenation of the string to MY_JSON produces an error because most likely your binary image data contains some non-prinatable characters.

I think you should encode the binary data from ifstream to base64 string and pass that encoded string to MY_JSON. On the server side decode the data in image field using base64-decoding.

The basic Base64 encoding/decoding for C++ can be found here: http://www.adp-gmbh.ch/cpp/common/base64.html

There are also questions on SO on how to decode Base64 in JS: How to send image as base64 string in JSON using HTTP POST?

P.S. Talking about sample code, you can first load your data to std::vector.

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

Then you call the

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

like this:

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

Finally, add the Code to JSON:

MY_JSON += Code;   // instead of ostrm.str
Community
  • 1
  • 1
Viktor Latypov
  • 14,289
  • 3
  • 40
  • 55
  • Worked perfectly. I was able to use the base64 string and build the json object using the expected functions instead of passing a string in.Thanks for the base64 encoding code. – yaegerbomb Apr 16 '15 at 17:15