yaegerbomb
yaegerbomb

Reputation: 1188

Send image in http post via json object using cpprest

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?

Upvotes: 2

Views: 3742

Answers (1)

Viktor Latypov
Viktor Latypov

Reputation: 14467

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

Upvotes: 3

Related Questions